输入/输出问题与简单的程序。

时间:2014-02-24 05:44:01

标签: c++ input

我有一份家庭作业,我遇到了一些麻烦。我似乎没有错误,但是当我运行程序并输入文本时......没有任何反应。

例如,为了测试它,我通常会输入“Robertson,Bob John”并点击输入。任何人都可以帮我这个吗?

#include <iostream>
#include <string> 

using namespace std;

int main () {

//Title and instructions
cout << "This program will output your name in first-to-last order!" << endl;
cout << "Please type your name in the following manner: last, first middle."; << endl;

//Declare the strings being used
string firstName;
string middleName;
string lastName;

//Put user input into strings, ignore the comma
cin >> lastName >> firstName >> middleName >> endl;
cin.ignore(',');

//Output the name in first-to-last order
cout << "Your name is: " << first <<' '<< middle <<' '<< last << endl;

//Pause before exiting
return 0;

}

2 个答案:

答案 0 :(得分:1)

既然你说它编译,可能你的真实代码在第二行;行没有流氓cout,不会尝试读入endl,并使用在最终cout中更正变量名称。

假设没有其他差异,问题是:

cin.ignore(',');

我不确定你想要做什么;但是等到你继续输入额外的44个字符(在其名称之后解释','作为其ASCII值44)之前它会等待。

如果你想忽略姓氏后面的逗号,可能最容易用逗号读取它,然后用lastName.pop_back()删除它(也许先检查那里是否有逗号)。

顺便说一句,我父亲没有中间名,而我姐姐有两个。他们不被允许使用您的程序吗?

答案 1 :(得分:0)

首先,您有一些编译错误;当您尝试cout输出时,您的第二个cout上会有一个额外的分号,错误的变量名称等等。但真正的问题是您的cin.ignore(',');。它似乎因某种原因而悬挂。我将根据the cin documentation猜测,它将逗号解释为数字,它会忽略那么多字符。

您需要在cin之后自行删除逗号;我把它作为锻炼留给你了。

#include <iostream>
#include <string>

using namespace std;

int main () {

//Title and instructions
cout << "This program will output your name in first-to-last order!" << endl;
cout << "Please type your name in the following manner: last, first middle." << endl;

//Declare the strings being used
string firstName;
string middleName;
string lastName;

//Put user input into strings, ignore the comma
cin >> lastName >> firstName >> middleName;

//Output the name in first-to-last order
cout << "Your name is: " << firstName <<' '<< middleName <<' '<< lastName << endl;

//Pause before exiting
return 0;

}
相关问题