通过运算符输入多个字符串>> C++
Input multiple strings via operator>> c++
制作如下代码:
#include <string>
#include <iostream>
using namespace std;
int main() {
string s;
while(true) {
cin >> s;
cout << "type : " << s << endl;
}
}
控制台的输出是:
输入:usa americ england gana
输出:
type : usa
type : americ
type : england
type : gana
输入:hello world
输出:
type : hello
type : world
每当我键入 "usa americ englend gana" 然后输入时,它会在 while 块中显示通过 cin 输入的每个字符串。
这有什么原因吗? "stream buffered"怎么样?
我怎样才能使通过 cin 输入多个字符串时,没有空格分隔?这个问题有什么特别的功能或答案吗?
对 std::cin
的 operator>>
的一次调用仅读取到第一个空格。当您在一行中输入 4 个单词时,您的 std::cin
会读取第一个单词,接受它,然后继续执行。但剩下的 3 个词仍在输入流中等待读取,它们将在下次调用 operator >>
时读取。
所以,为了说明会发生什么,这里有一个例子:
Input stream content: [nothing]
//(type usa americ england gana)
Input stream content: usa americ england gana
//cin >> s;
s == "usa"
Input stream content: americ england gana
//cin >> s;
s == "americ";
Input stream content: england gana
//etc.
您可能想尝试 std::getline
to read whole lines instead. Just don't mix std::cin and std::getline。
while(true) {
std::getline(std::cin, s)
cout << "type : " << endl;
}
制作如下代码:
#include <string>
#include <iostream>
using namespace std;
int main() {
string s;
while(true) {
cin >> s;
cout << "type : " << s << endl;
}
}
控制台的输出是:
输入:usa americ england gana
输出:
type : usa
type : americ
type : england
type : gana
输入:hello world
输出:
type : hello
type : world
每当我键入 "usa americ englend gana" 然后输入时,它会在 while 块中显示通过 cin 输入的每个字符串。
这有什么原因吗? "stream buffered"怎么样?
我怎样才能使通过 cin 输入多个字符串时,没有空格分隔?这个问题有什么特别的功能或答案吗?
对 std::cin
的 operator>>
的一次调用仅读取到第一个空格。当您在一行中输入 4 个单词时,您的 std::cin
会读取第一个单词,接受它,然后继续执行。但剩下的 3 个词仍在输入流中等待读取,它们将在下次调用 operator >>
时读取。
所以,为了说明会发生什么,这里有一个例子:
Input stream content: [nothing]
//(type usa americ england gana)
Input stream content: usa americ england gana
//cin >> s;
s == "usa"
Input stream content: americ england gana
//cin >> s;
s == "americ";
Input stream content: england gana
//etc.
您可能想尝试 std::getline
to read whole lines instead. Just don't mix std::cin and std::getline。
while(true) {
std::getline(std::cin, s)
cout << "type : " << endl;
}