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

五迷三道 提交于 2019-12-11 04:09:07

问题


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.


回答1:


\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') ;



回答2:


This is an issue with reading using >> into a char array. It splits at whitespace when tokenizing. Try printing user_input to screen to confirm this.

Using getline into a std::string is generally safer in this context (as mentioned by daknøk). And I assume the input is likely to be terminated by a carriage return?

std::string user_input;
std::getline( std::cin, user_input, '\n' );



回答3:


This is because your input stops reading when white space is entered. You can use

cin.unsetf(ios::skipws)

By default it is set to skip white spaces. With this you will get your desired result.



来源:https://stackoverflow.com/questions/13014272/c-user-input-check-for-0-stops-at-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!