2

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.

3 Answers3

9

\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') ;
Coding Mash
  • 3,338
  • 5
  • 24
  • 45
  • 2
    How does the user enter a null character from the keyboard? Is that even possible? – Benjamin Lindley Oct 22 '12 at 15:14
  • @BenjaminLindley you can pipe to `stdin`. The keyboard is irrelevant. – daknøk Oct 22 '12 at 15:15
  • @daknøk: Okay. Is that what's really wanted here though? I'm pretty sure the OP's intention is to just read until a newline. (from a user who is using a keyboard) – Benjamin Lindley Oct 22 '12 at 15:16
  • The answer isn't really correct, since `cin >> user_input;` stops at any white space, not just a space character, and it skips any leading white space as well. – James Kanze Oct 22 '12 at 16:13
3

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' );
Alex Wilson
  • 6,690
  • 27
  • 44
  • When inputting to a string, you have to use the free function form of `getline`: `std::getline( std::cin, user_input );`. (The default is `'\n'`, so you don't have to specify it. And it is `'\n'`, and not `"\n"`, which shouldn't compile.) – James Kanze Oct 22 '12 at 16:14
  • @JamesKanze You are correct in every point. I was being somewhat careless. My apologies. Fixed now. – Alex Wilson Oct 22 '12 at 16:23
1

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.

LAP
  • 122
  • 1
  • 4
  • 14