将cin的输出分配给变量 [英] Assigning the output of cin to variables
问题描述
我正在尝试学习如何使用 cin
和 getline
编写一个纸质分级程序,我可以在学校使用。对于初学者来说这是一个棘手的项目,但它让我知道了我需要学习的知识,这是我需要做的第一件事。
I'm trying to learn how to use cin
and getline
to write a paper grading program that I can use at school. It's kind of a tricky project for a beginner but it lets me know what I need to learn and this is the first thing I need to do.
int main()
{
string grader;
int x;
cout << "Who will I be assisting today? ";
getline (cin, grader);
cout << "Hello " << grader << ".\n";
cout << "How manny questions are on the test you will be grading? ";
getline (cin, x);
cout << "this is a " << x << "question test graded by" << grader << ".\n";
}
让我说我回答了第一个问题的John Doe,然后回答了第二个问题的20 。我希望它打印这是John Doe分级的20个问题的测试。
我哪里出错了?
我敢肯定这是一个愚蠢的错误,但却困扰着我。我是新手,为您的无知感到抱歉。我将对此程序有更多与用户输入无关的问题。是否可以在此处发布这些问题或开始新话题?
谢谢
Lets say I answered John Doe for the first question, then 20 for question two. I want it to print "this is a 20 question test graded by John Doe"
Where am I going wrong?
I'm sure it's a stupid mistake but it's bugging me. I'm a novice so sorry for the ignorance. I will have more questions regarding this program that will not have to do with user in-put. is it ok to post these questions here, or start new topics?
thanks
推荐答案
由于您未说明错误原因,而且还可能是缺少include /命名空间。
完整的可运行/可编译程序将是:
Since you did not state what was your error, and alas it could also be a missing include/namespace. The complete runnable/compilable program would be:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string grader;
int x;
cout << "Who will I be assisting today? ";
getline (cin, grader);
cout << "Hello " << grader << ".\n";
cout << "How manny questions are on the test you will be grading? ";
cin >> x;
cout << "this is a " << x << "question test graded by" << grader << ".\n";
}
无论如何,这将在您输入问题数量后立即关闭(或从shell / cmd调用您的exe文件)-所以不要怀疑您是否看不到结果。
anyway, this will immediatly close after you entered the amount of questions (or you call your exe from a shell/cmd) - so dont wonder if you cant see the result.
这篇关于将cin的输出分配给变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!