cin函数是否在输入末尾添加以null结尾的空值? [英] Does the cin function add null terminated at the end of input?

查看:118
本文介绍了cin函数是否在输入末尾添加以null结尾的空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我声明一个字符数组: char arr [200]
,然后我随后使用cin函数将值读入 arr [200]
,然后在命令行窗口中键入:abcd

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

是否有空终止: \0 会在输入末尾自动添加到数组吗?

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

(我不这么认为,因为我已经对其进行了测试使用cin函数:cin >> abcd)

(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++




    }

我的计数值将不是4,而是像43,因此我得出结论,在cin函数之后,字符数组不是以null结尾的

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

推荐答案

std :: istream 到字符数组的格式化输入将使输入为空终止,如C ++ 11 27.7.2.2.3 / 9:

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>> 然后存储一个空字节( charT())在下一个位置

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

您发布的代码给出了预期的结果一旦解决了明显的语法错误。但是请注意,这非常危险;没有检查数组的长度,因此太多的输入将使它溢出。我强烈建议您使用 std :: string 类(而不是纯字符数组)来管理字符串。

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.

这篇关于cin函数是否在输入末尾添加以null结尾的空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆