Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isalpha() function not working for spaces in string [duplicate]

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

like image 650
purple_tulip Avatar asked May 29 '26 13:05

purple_tulip


2 Answers

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

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

like image 54
Jiří Baum Avatar answered Jun 01 '26 03:06

Jiří Baum


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.

like image 39
Deepak Patankar Avatar answered Jun 01 '26 03:06

Deepak Patankar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!