Thursday 30 June 2016

C++ Code to Remove All Characters Except Letters and Spaces

C++ Code to Remove All Charactes Except Letters and Spaces

Description: In the following C++ Intro. to Computing code, user gives an input string which is taken in a char array and the code removes all characters except LETTERS and SPACE.

#include <iostream>
using namespace std;

int main()
{
     bool nchr=false;
     char input[1000],temp;
     int lenght,i=0,j=0,k;
    
cout<<"Please enter a string\n\n";
     gets(input);
     
     lenght=strlen(input);
     k=lenght;
    
while(i<k){
           nchr=false;
          
if ( (input[i]<'A' || input[i]>'Z') && (input[i]<'a' || input[i]>'z') && input[i]!=' ' ){
                nchr=true;

                for (j=i;j<k-1;j++){
                     temp=input[j];
                     input[j]=input[j+1];
                     input[j+1]=temp;
                }
           }

           if (nchr==true){
                k--;
                lenght--;
           }
           else
                i++;
     }

     input[lenght]='\0';
     cout<<endl<<input<<endl;

     return 0;
}

No comments

Post a Comment

Recent Posts