Assigning the output of cin to variables

こ雲淡風輕ζ 提交于 2019-12-13 00:25:05

问题


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";
}

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


回答1:


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";
}

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.



来源:https://stackoverflow.com/questions/15131772/assigning-the-output-of-cin-to-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!