C++ getline()只读取第二个单词(bug)
我试图制作一个程序,读入一个名字,然后打印出来。我想使用C++ getline()只读取第二个单词(bug),c++,C++,我试图制作一个程序,读入一个名字,然后打印出来。我想使用getline,这样它将读取整行内容,因此名称中可以有任意数量的单词。(这就是为什么我不想只使用cin两次)但它只打印第二个单词。怎么了 输入:Rock Lee #include <iostream> #include <iomanip> #include <string> using namespace std; int main () { string name; cout &
getline
,这样它将读取整行内容,因此名称中可以有任意数量的单词。(这就是为什么我不想只使用cin
两次)但它只打印第二个单词。怎么了
输入:Rock Lee
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main () {
string name;
cout << "Enter your name: ";
cout.flush();
cin >> name;
getline(cin, name, '\n');
if (name == "")
{
cout << "Name is blank.";
return -1;
}
cout << name;
return 0;
}
输出:Lee
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main () {
string name;
cout << "Enter your name: ";
cout.flush();
cin >> name;
getline(cin, name, '\n');
if (name == "")
{
cout << "Name is blank.";
return -1;
}
cout << name;
return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main(){
字符串名;
姓名;
getline(cin,名称,'\n');
如果(名称==“”)
{
库特
从输入流中读取“Rock”并将其安全保存在name
中。流现在包含“Lee\n”。现在
从流中读取剩余的“Lee\n”,丢弃\n
,然后用结果覆盖name
。name
现在包含“Lee”
要将整行内容读入name
,请删除“窃取”第一个单词的cin
行
顺便说一句,不需要cout.flush();
,因为cout
和cin
在默认情况下是绑定的,即当控件到达cin
时,cout
将始终刷新
getline(cin, name, '\n');