Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++, user input check for '\0' stops at spaces?

If the user inputs a sentence containing spaces the while loop stops at one of these spaces. Why is this happening? are '\0' and a space the same or did i do something else wrong?

int main ( )
{
    char user_input[200];
    cin>>user_input;
    int i=0;
    while(user_input[i]!='\0')
    {
        i++;
    }
    cout<<i;
    return 1;

}

Thanks everyone, I appreciate your help.

like image 579
user1765737 Avatar asked Dec 09 '25 15:12

user1765737


1 Answers

\0 is the null terminating character with ASCII code 0. Space is another character with ASCII 32 i suppose. In fact you are doing this.

cin >> user_input;

It takes input till you press space or enter. So no space is present in your user_input string. Use this instead of cin.

cin.getline (user_input, 200, '\0') ;
like image 199
Coding Mash Avatar answered Dec 12 '25 06:12

Coding Mash



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!