std::cin 是一个std::basic_istream,可以这样操作。
通常,您会使用>> 或getline 来读取流。这两句话都写着“知道何时停止”。
但是,如果您想使用\ns 查看缓冲区,则假定您将从控制台传递带有换行符的流,并且您用来读取它的函数不会“吃掉”换行符。
您可以copy the buffer to a string。但请记住,您将不得不以其他方式signal the EOF。
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::ostringstream oss{};
oss << std::cin.rdbuf();
std::string all_chars{oss.str()};
std::cout << all_chars;
return 0;
}
在 Windows 上,如果我输入 hello输入there输入 后跟 Ctl+z (Windows 必须换行)然后我看到:
hello
there
^Z
hello
there
所以在本例中,包括换行符在内的所有内容都存储在 std::string 中。
但我只看到 \n 的行尾。我以为Windows应该
使用\r \n 作为行尾
我添加了以下内容以明确显示各个字符:
int index{};
for(auto mychar : all_chars)
std::cout << std::setw(3) << index++ << ": character number " << std::setw(5) << static_cast<int>(mychar)
<< " which is character\t"<< ((mychar == 10) ? "\\n" : std::string{}+mychar) << '\n';
对于它产生的相同输入:
hello
there
^Z
hello
there
0: character number 104 which is character h
1: character number 101 which is character e
2: character number 108 which is character l
3: character number 108 which is character l
4: character number 111 which is character o
5: character number 10 which is character \n
6: character number 116 which is character t
7: character number 104 which is character h
8: character number 101 which is character e
9: character number 114 which is character r
10: character number 101 which is character e
11: character number 10 which is character \n
所以这表明只有\ns 从控制台传递,没有找到\rs。我使用 Windows 10 进行此测试,但我想这已经有一段时间了。