c++ - cin.getline 将字符串的开头设置为 '\0'

标签 c++ iostream getline cin

我在 Visual C++ 2010 上运行这段代码

char c[10];
cin.get(&c[0],5);
cin.get(&c[2],4);
cout << c << endl;

如果我将“123456789”输入到cincout子句将打印“12567”,这就是我期望的结果。

但是如果我写:

char c[10];
cin.getline(&c[0],5);
cin.getline(&c[2],4);
cout<< c <<endl;

并输入相同的字符串,它只会显示“12”,其中 c=={'1','2','\0','4','\0'}

根据 documentation , cin.get 和 cin.getline 之间的区别在于 cin.get 不会像 cin.getline 那样丢弃 delim 字符,所以我不知道为什么会发生这种情况。谁能给我提示吗?

最佳答案

发生的情况是,如果 basic_iostream::getline() 达到要读取的字符限制(streamsize 参数减 1),它将停止读取,然后放置到目前为止已读取的数据后的空字符。它还在流上设置failbit

因此,假设流已准备好读取“123456789”,当您调用cin.get(&c[0],5)时,数组将获得{'1','2','3','4','\0'} 放置到元素 04 中。并且在流上设置了failbit

现在,当您调用 cin.get(&c[2],4) 时,failbit 会在流上设置,因此不会读取任何内容。 getline() 调用什么也不做,只是将终止 null 放入数组的索引 2 处(即使没有从流中读取任何内容,getline() code> 将放置空字符 - 即使未读取是由于 failbit)。所以数组现在看起来像:

{'1','2','\0','4','\0'}

您链接到的文档提到了这一点:

If the function stops reading because this size is reached, the failbit internal flag is set.

但是 getline() 做了很多事情,所以很容易错过这个细节。

关于c++ - cin.getline 将字符串的开头设置为 '\0',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9796176/

相关文章:

c++ - 查找预编译头文件时跳过

c++ - 派生 basic_ostream : "using" keyword and ambiguous overload for operator <<

java - 如何将 map 集合写入文件并读取它?

C++条件编译

c++ - 如何在 C/C++ 中编写一个简单的整数循环缓冲区?

c++ - move 构造函数未被调用

具有来自服务器 : Socket (using streams) or Apple Push Notification service? 的实时更新的 iOS 应用程序

c++ - getline() valgrind 内存泄漏

C++ getline() 跳过空字符串

c++ - 为什么从管道读取时 libc++ getline 会阻塞,而 libstdc++ getline 不会?