混合cin和getline输入问题 [英] mixing cin and getline input issues
问题描述
我正在用c ++入门做练习,并试图做一个程序来接收输入的单词和一行.如果当我要求输入一个单词(使用cin)时,请按Enter键,那么程序仅跳过下一行,而不要求输入一行(使用getline)...并且如果我在cin中写了一个完整的短语(例如"hello beautifull world"),然后第一个单词("hello")被cin捕获,其他两个单词("beautifull world")被getline捕获.
我知道在cin中,当我输入空格时,它会削减输入.我不明白的是两件事:
1.--为什么如果我用Enter结束输入(在cin中),它会跳过所有其余代码? (有解决方案吗?)
2.-为什么要在cin中写一个完整的短语,为什么要在执行之前将另外两个单词分配给getline cout<< 输入一行"<<恩德尔 ?
谢谢!对不起,我的英语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;
}
在两个输入之间需要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;
}
对于第二个答案,当您在第一个cin
中输入整个字符串时,它仅占用一个单词,其余部分由getline
占用,因此您的程序将在不获取getline
Im doing exercices from c++ primer, and trying to do a program that recieves as input a word and a line. If when i ask for a word (with cin) I press enter, then the program just skips the next lines and doest ask for a line (with the getline)... and if i write an entire phrase in the cin (like "hello beautifull world") then the first word ("hello") is captured by the cin and the others two words ("beautifull world") by the getline.
i understand that in the cin, when i input a space, it cuts the input. what i dont uderstand are two things:
1.- why if i end the input (in the cin) with enter it skips all the rest of code? (is there a solution for that?)
2.- why if i write an entire phrase in the cin, it assign the other two word to the getline before to execute the cout << "enter a line" << endl; ?
Thx! sorry for my english 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;
}
You need cin.ignore() between two inputs:because you need to flush the newline character out of the buffer in between.
#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;
}
For your second answer, when you enter whole string in first cin
, it takes only one word, and the rest is taken by getline
and thus your program will execute without taking input from getline
这篇关于混合cin和getline输入问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!