C ++控制台应用程序循环

时间:2013-12-30 15:37:09

标签: c++ cycle cin

我有控制台应用程序,我首先生成10个学生,然后我将它们添加到Evidence(自己的双链表)。然后我将学生从Evidence移除,但在第二次(或更高)移除学生后,我有无限循环,因为cin >> id;不等我的反应。请问哪里有问题?感谢所有的建议,抱歉我的英语不好。 : - )

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include "EvidenceStudent.h"
using namespace std;

int main(int argc, char ** argv[])
{
    EvidenceStudent * evidence = new EvidenceStudent();
    int number;
    while(1){
            << "[1] Generate 10 students" << std::endl
            << "[2] Remove student" << std::endl
            << "[3] Write all students" << std::endl
            << "Number: ";
        std::cin >> number;
        cin.ignore();
        switch(number){
        case 1 : {
            Student * s0 = new Student("st00000", "Karel", "Gott");
            Student * s1 = new Student("st11111", "Marek", "Prima");
            Student * s2 = new Student("st22222", "Alois", "Jirasek");
            Student * s3 = new Student("st33333", "Josef", "Rehak");
            Student * s4 = new Student("st44444", "Zdenek", "Zlatnik");
            Student * s5 = new Student("st55555", "Monika", "Svobodova");
            Student * s6 = new Student("st66666", "Michal", "Cvik");
            Student * s7 = new Student("st77777", "Jiri", "Sadilek");
            Student * s8 = new Student("st88888", "Tomas", "Svoboda");
            Student * s9 = new Student("st99999", "Vojtech", "Hudec");

            evidence->AddStudent(*s0, Student::FIRST);
            evidence->AddStudent(*s1, Student::LAST);
            evidence->AddStudent(*s2, Student::NEXT);
            evidence->AddStudent(*s3, Student::PREVIOUS);
            evidence->AddStudent(*s4);
            evidence->AddStudent(*s5, Student::FIRST);
            evidence->AddStudent(*s6, Student::LAST);
            evidence->AddStudent(*s7, Student::NEXT);
            evidence->AddStudent(*s8, Student::PREVIOUS);
            evidence->AddStudent(*s9);
            break;
                 }
        case 2 : {
            string id;
            cout << "Enter student ID: ";
            cin >> id;       //<-- after entering second id - infinite cycle
            cin.ignore();        
            evidence->RemoveStudent(id); 
            break;
                 }
        case 3 : evidence->WriteAllStudents(); break;
        default : cout << "Bad number." << endl; break;
        }
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

参见运算符的操作&gt;&gt; oftream:http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/

由于转换为int失败,您可能在cin上设置了失败位,之后调用

std::cin >> number;

将失败,导致程序永远不会从std :: cin接收输入并进入无限循环。