Search code examples
c++user-inputc-strings

Does the cin function add null terminated at the end of input?


If I declare a character array: char arr[200] and then I subsequently use the function cin to read values into arr[200] and I type into the command window line: abcd

Is there a null terminated: \0 automatically added to the array at the end of the input?

(I don't think so because I tested it using the cin function: cin>>abcd )

Can somebody explain it to me why?

Below is a snippet of my code I use to test

    char arr[200]
    int count=0;
    int i=0;
    cin>>arr // i type into command window:abcd

    while (arr[i] != '\0')
    {
       count++;
        i++




    }

My count value will not be 4 but like 43 hence I concluded that the character array is not null terminated after the cin function


Solution

  • Formatted input from a std::istream into a character array will null-terminate the input, as specified in C++11 27.7.2.2.3/9:

    operator>> then stores a null byte (charT()) in the next position

    The code you've posted gives the expected result once the obvious syntax errors are fixed. But beware that this is very dangerous; there is no check on the length of the array, so too much input will overflow it. I strongly recommend you use the std::string class, rather than plain character arrays, for managing strings.

    The code you posted in a comment via a link looks like this:

    char array[20];
    int length=getlength(array);
    cin>>array;
    

    reading into the array after attempting to measure the string length of the uninitialised array. This could give any result, or crash, or cause any other example of undefined behaviour.

    In future, you should make sure that the code you post in your question is the same code that exhibits the behaviour you're asking about; otherwise, it's impossible to answer the question.