gpt4 book ai didi

我的教授无法弄清楚的 C++ 循环错误

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:51 25 4
gpt4 key购买 nike

我目前正在学习 C++ 编程类(class),并且正在从事一个项目,我必须在其中创建一个相当简单的电影数据库。我的代码基本上按预期工作,但在某些情况下它会导致主菜单无限循环,我无法弄清楚原因。我把它带给我的老师,他也无法解释。他给了我一个解决方法,但我想知道是否有人可以看到问题的原因。完整代码如下:

#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>

using namespace std;

struct MovieType
{
string title;
string director;
int year;
int length;
string rating;
};

MovieType addMovie() {
MovieType newMovie;

cout << "Movie title :";
getline(cin, newMovie.title);
cout << "Director :";
getline(cin, newMovie.director);
cout << "Year :";
cin >> newMovie.year;
cout << "Length(in minutes) :";
cin >> newMovie.length;
cout << "Rating :";
cin >> newMovie.rating;
cout << endl;

return newMovie;
}

void listMovie(MovieType movie) {
cout << "______________________________________" << endl;
cout << "Title : " << movie.title << endl;
cout << "Director : " << movie.director << endl;
cout << "Released : " << movie.year << endl;
cout << "MPAA Rating : " << movie.rating << endl;
cout << "Running time : " << movie.length << " minutes" << endl;
cout << "______________________________________" << endl;
}

void search(vector<MovieType> movieVector) {
string strSearch;
cout << endl << "Search title: ";
getline(cin, strSearch);
for (int c = 0; c < movieVector.size(); c++) {
if (movieVector.at(c).title == strSearch)
listMovie(movieVector.at(c));
}
}

int main() {
bool quit = 0;
vector<MovieType> movieVector;

while (quit == 0) {
char selection = 'f';

cout << "Main Menu:" << endl;
cout << "'a' - Add movie" << endl;
cout << "'l' - List movies" << endl;
cout << "'s' - Search by movie title" << endl;
cout << "'q' - Quit" << endl;
cout << "Please enter one of the listed commands:";
cin >> selection;
cin.ignore();
cout << endl;
if (selection == 'a')
movieVector.push_back(addMovie());
else if (selection == 'l') {
for (int c = 0; c < movieVector.size(); c++) {
listMovie(movieVector.at(c));
}
}
else if (selection == 's') {
search(movieVector);
}
else if (selection == 'q')
quit = 1;

}
return 0;
}

当在 addMovie 函数中输入了一个意外的输入类型(比如输入 int 类型的文本)时,它只是运行函数然后无限循环菜单。在我看来,代码只是停止查看输入流。我已经尝试在许多不同的地方使用 cin.ignore(),但如果流中没有任何内容,它会继续运行并不重要。我正在使用 NetBeans 来编译我的代码。我真的不知道为什么它会这样,否则我会提供更多信息,但我只是好奇为什么会这样,因为正如我之前所说,我的教授甚至不知道为什么会这样。非常感谢任何帮助或见解。

最佳答案

cin 进入错误状态,其中 cin.fail() 为真。在这种状态下,它只是忽略所有输入操作。一种修复方法是清除错误状态,但更好的是,只对 cin 使用 getline 操作,而不是格式化输入。

例如,而不是

cin >> newMovie.year;

...做

newMovie.year = stoi( line_from( cin ) );

... 其中 line_from 可以定义为

auto line_from( std::istream& stream )
-> std::string
{
std::string result;
if( not getline( stream, result ) )
{
// Throw an exception or call exit(EXIT_FAILURE).0
}
return result;
}

免责声明:编译器未修改代码。

关于我的教授无法弄清楚的 C++ 循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34193028/

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