首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++ CIN cin随机跳过

C++ CIN cin随机跳过
EN

Stack Overflow用户
提问于 2010-04-07 00:55:33
回答 1查看 836关注 0票数 2

我有这个程序,但是cin在随机跳过..我的意思是有时会,有时不会。你有什么办法解决这个问题吗?

代码语言:javascript
复制
    int main(){ 


        /** get course name, number of students, and assignment name **/
        string course_name;
        int numb_students;
        string assignment_name;
        Assignment* assignment;

        cout << "Enter the name of the course" << endl;
        cin >> course_name;

        cout << "Enter the number of students" << endl;
        cin >> numb_students;   

        cout << "Enter the name of the assignment" << endl;
        cin >> assignment_name;

        assignment = new Assignment(assignment_name);

        /** iterate asking for student name and score **/
        int i = 0;
        string student_name;
        double student_score = 0.0;
        while( i < numb_students ){

            cout << "Enter the name for student #" << i << endl;
            cin >> student_name;
            cout << "Enter the score for student #" << i << endl;
            cin >> student_score;
            assignment->addScore( Student( student_name, student_score ));
            i++;
        }
}

好了,我想通了。对于任何想知道的人来说,这里有更新的代码:

代码语言:javascript
复制
int main(){ 

    /** get course name, number of students, and assignment name **/
    string course_name;
    int numb_students;
    string assignment_name;

    cout << "Enter the name of the course" << endl;
    getline(cin, course_name);

    cout << "Enter the number of students" << endl;
    string temp;
    getline(cin, temp);
    numb_students = atoi(temp.c_str());

    cout << "Enter the name of the assignment" << endl;
    getline(cin, assignment_name);

    Assignment assignment(assignment_name);

    /** iterate asking for student name and score **/
    int i = 0;
    string student_name;
    double student_score = 0.0;
    while( i < numb_students ){

        cout << "Enter the name for student #" << i+1 << endl;
        getline(cin, student_name);     
        cout << "Enter the score for student #" << i+1 << endl;
        getline(cin, temp);
        student_score = atof(temp.c_str());
        assignment.addScore( Student( student_name, student_score ));
        i++;
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-04-07 01:00:29

我猜您的一些输入中有空格,>>操作符将其视为特定输入项的末尾。iostreams >>操作符实际上不是为交互式输入而设计的,特别是对于字符串-您应该考虑使用getline()来代替。

此外,您还不需要使用动态分配:

代码语言:javascript
复制
assignment = new Assignment(assignment_name);

最好写成:

代码语言:javascript
复制
Assignment assignment(assignment_name);

你应该尽可能避免在你的代码中使用'new‘,而是让编译器为你关注对象的生命周期。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2586681

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档