我刚刚开始一个入门级的C ++课程,我正在完成我的第一个家庭作业。代码似乎工作得很好,除非输入中包含一个空格,然后它只是跳过输入所在行之后的其余问题。
我希望这是有道理的!
// This program prompts the user a few general questions about themselves, the date, which IDE they are using, and which machine they have downloaded the IDE on to.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string userName, currentDate, softwareName, machineName;
//Ask the user his name.
cout << "What is your name? ";
cin >> userName;
//Ask the user the date.
cout << "What is the date? ";
cin >> currentDate;
//Asks the user which software he downloaded.
cout << "What is the name the IDE software you downloaded? ";
cin >> softwareName;
//Asks the user which machine he downloaded his IDE on.
cout << "Which machine did you download the IDE on? (ie. home computer, laptop, etc.) ";
cin >> machineName;
//Prints out the users inputs going downwards.
cout << "" << userName << endl;
cout << "" << currentDate << endl;
cout << "" << softwareName << endl;
cout << "" << machineName << endl;
return 0;
}
答案 0 :(得分:0)
提取运算符(>>
)将读取输入,直到空格或下一行(可能还有其他空白字符,但我不确定)。因此,当您键入带空格的内容时,空格后面的部分将被解释为下一个问题的答案。要使用空格读取输入,请使用getline()
函数,默认情况下不会停止在空格处读取,如下所示:getline(cin, userName)
。请注意,提取运算符将在输入流中留下下一行,这将导致后续getline()
调用以提供空字符串。在提取后调用cin.ignore()
之前,请务必致电getline()
。我试图尽可能简单地解释这一点,希望你能理解这一点。