Gar*_*rdo 1 c++ string 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 << "your word is " << word << endl;
cout << "your line is " << line << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您需要在两个输入之间使用 cin.ignore() :因为您需要将换行符从中间的缓冲区中刷新出来。
#include <iostream>
using namespace std;
int main() {
string word, line;
cout << "enter a word" << endl;
cin >> word;
cout << "enter a line" << endl;
cin.ignore();
getline(cin,line);
cout << "your word is " << word << endl;
cout << "your line is " << line << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
对于你的第二个答案,当你在第一个输入整个字符串时cin,它只需要一个单词,其余的将被接受getline,因此你的程序将在不接受输入的情况下执行getline
| 归档时间: |
|
| 查看次数: |
15313 次 |
| 最近记录: |