isalpha() function not working for spaces in string

331 Views Asked by At

I wrote a code so that it removes everything(like spaces and other things) other than the alphabats using isalpha() function and converts it to lower case using tolower() function. It is working fine if i don't put a space in the string but if there is any space in the string then it go beyond the space. I dont understand why this is happening. This is the code i wrote.

#include<bits/stdc++.h>
#include<cstring>
#include<cctype>
using namespace std;
int main()
{
    int i;
    string A,b="";
    cin>>A;
    for(i=0;i<A.size();i++)
    {
        if(isalpha(A[i]))
        b+= tolower(A[i]);
        
        else
        continue;
        
    }
    cout<<b;
}

Please help me. Thankyou

2

There are 2 best solutions below

0
On

The cin >> A; considers the space to terminate the input.

To get the whole line, use getline(cin, A);

0
On

cin reads the string till the first space it encounters, if your input string is "Hello World", then cin will only read "Hello".

You can use getline function to read a complete line.