通过operator >> c ++输入多个字符串[关闭]

问题描述 投票:-2回答:1

以下代码:

#include <string>
#include <iostream>
using namespace std;

int main() {
 string s;

 while(true) {
 cin >> s;
 cout << "type : " << s << endl;
 }
}

控制台的输出是:

输入:usa americ england gana

OUTPUT:

type : usa
type : americ
type : england 
type : gana

输入:hello world

OUTPUT:

type : hello
type : world

每当我输入“usa americ englend gana”然后输入时,它会在while块中显示通过cin输入的每个字符串。

这有什么理由吗? “流缓冲”怎么样?

我怎么能这样做,以便每当通过cin输入多个字符串时,没有空格分隔?这个问题有什么特别的功能或答案吗?

c++ stream buffer cin
1个回答
2
投票

operator>>std::cin的一次调用只能读到第一个空格。当您在一行中输入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来读取整行。 Just don't mix std::cin and std::getline

while(true) {
    std::getline(std::cin, s)
    cout << "type : " << endl;
}
© www.soinside.com 2019 - 2024. All rights reserved.