小编Gar*_*rdo的帖子

混合 cin 和 getline 输入问题

我正在做 C++ 入门练习,并尝试编写一个接收单词和一行作为输入的程序。如果当我询问一个单词(使用 cin)时,我按 Enter 键,那么程序只会跳过下一行,并且不会询问一行(使用 getline)...如果我在 cin 中写下整个短语(例如“ hello beautifull world") 然后第一个单词 ("hello") 由 cin 捕获,其他两个单词 ("beautifull world") 由 getline 捕获。

我知道在 cin 中,当我输入空格时,它会切断输入。我不明白的是两件事:

1.- 为什么如果我用 Enter 结束输入(在 cin 中),它会跳过所有其余代码?(有解决办法吗?)

2.- 为什么如果我在 cin 中写下整个短语,它会在执行 cout << "enter a line" << endl; 之前将另外两个单词分配给 getline; ?

谢谢!对不起我的英语 C:

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

 int main() {

string word, line;

cout << "enter a word" << endl;
cin >> word;

cout << "enter a line" << endl;
getline(cin, line);

cout …
Run Code Online (Sandbox Code Playgroud)

c++ string getline

1
推荐指数
1
解决办法
2万
查看次数

标签 统计

c++ ×1

getline ×1

string ×1