2010-04-06 132 views
2

我有这个程序,但随机跳过cin ..我的意思是有时它会,有时它不会。任何想法如何解决这一问题?C++ cin cin随机跳过

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

好的我想通了。对于任何人想知道这里是更新后的代码:

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++; 
    } 
+0

'随机跳过'是什么意思?你可以说得更详细点吗? – 2010-04-06 17:00:25

+3

'numb_students'岩石:D – pajton 2010-04-06 17:01:02

+0

numb_students:如何真实;-) – JRL 2010-04-06 17:01:29

回答

5

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

而且,你是不必要使用动态分配:

assignment = new Assignment(assignment_name); 

会好得多写为:

Assignment assignment(assignment_name); 

你应该避免在你的代码中使用“新”的只要有可能,和而是让编译器为你处理对象的生命周期。

+0

是的,我的输入有空格....我会尽力得到线条感谢 – user69514 2010-04-06 17:02:50