【发布时间】:2015-06-15 16:58:45
【问题描述】:
在该程序的每个输入中,我希望用户能够输入他们想要的任意数量的“单词”(意思是由空格/制表符分隔的文本)......但不允许用户输入单词超出当前的 cin。例如:如果我输入 John Smith Doe,我希望将 John 放入“name”中,并丢弃 Smith 和 Doe。然后我想输入“年龄”和“体重”,而不需要让 Smith 变老而 Doe 变重。目前,如果我输入 John Doe 作为名称,那么年龄将变为 Doe。如果我输入 John Smith Doe 作为名称,则年龄变为 Smith,体重变为 Doe。 有人可以帮忙吗?
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
string name;
string age;
string weight;
//user can enter more than one name (title, first, middle, last, etc.)
cout << "Enter your name: " << endl;
cin >> name;
//if user entered two or more names above,
//disallow cin from putting name two into 'age'
cout << "Enter your age: " << endl;
cin >> age;
//same thing for weight
cout << "Enter your weight: " << endl;
cin >> weight;
cout << "You typed: " << endl;
cout << "Name: " << name << endl;
cout << "Age: " << age << endl;
cout << "Weight: " << weight << "." << endl;
return 0;
}
【问题讨论】:
-
你想要 std::getline(stream, string)
-
你只需ignore它。
-
当您的代码提示输入姓名时,您的代码是否跳过了“标题”输入?为什么您的 cmets 使用“first”、“middle”、“last”而不是“name”?也许你的提示是不够的。你能改进你的需求陈述吗?
-
这是最好的答案...特别是:getline(stream, string)。
标签: c++