gpt4 book ai didi

C++ CIN cin 随机跳过

转载 作者:搜寻专家 更新时间:2023-10-31 00:48:28 26 4
gpt4 key购买 nike

我有这个程序,但 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++;
}

最佳答案

我猜你的某些输入中有空格,>> 运算符将其视为特定输入项的结尾。 iostreams >> 运算符实际上并不是为交互式输入而设计的,尤其是对于字符串——您应该考虑改用 getline()。

此外,您不必要地使用动态分配:

assignment = new Assignment(assignment_name);

最好写成:

Assignment assignment(assignment_name);

您应该尽可能避免在代码中使用“new”,而是让编译器为您处理对象生命周期。

关于C++ CIN cin 随机跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2586681/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com