Does the cin function add null terminated at the e

2019-06-14 15:54发布

问题:

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

回答1:

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.



回答2:

Yes, the input will be zero-terminated. Otherwise you wouldn't be able to, for example, print it without printing random characters after your input.