gpt4 book ai didi

c++ - 超过 8 个字符的字符串会导致无限循环 C++

转载 作者:行者123 更新时间:2023-11-28 01:47:31 25 4
gpt4 key购买 nike

我的 C++ 代码有问题,而且我还没有真正在网上找到任何描述为什么我有这个问题的信息。这是我的代码:

/*
Write a program using vectors and iterators that allows a user to main-
tain a list of his or her favorite games. The program should allow the
user to list all game titles, add a game title, and remove a game title.
*/

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
vector<string> gamesList;
gamesList.reserve(10);
vector<string>::const_iterator iter;
string menu = "1. List all games\n";
menu += "2. Add a game title\n";
menu += "3. Remove a game title\n";
menu += "4. Quit\n";
string newTitle = "", removeTitle = "";
int choice = 0;

while (choice != 4)
{
cout << menu;
cout << "\nYour choice: ";
cin >> choice;
switch (choice)
{
case 1:
for (iter = gamesList.begin(); iter != gamesList.end(); ++iter)
{
cout << *iter << endl;
}
cout << "\nList capacity is " << gamesList.capacity() << endl;
break;
case 2:
cout << "Please enter a game title :";
cin >> newTitle;
gamesList.push_back(newTitle);
break;
case 3:
cout << "Which game title do you want to remove?\n";
cin >> removeTitle;
for (int i = 0; i < gamesList.size(); ++i)
{
if (gamesList[i] == removeTitle)
{
gamesList.erase(gamesList.begin() + i);
}
}
break;
case 4:
cout << "Good bye!";
break;
}
}
return 0;
}

如果我运行该程序并在列表中输入 Pong、Breakout 和 Tetris,它运行良好。如果我运行该程序并输入 Half Life 或任何长度超过 8 个字符的标题,该程序将进入无限循环。任何帮助将不胜感激。

最佳答案

问题不在于长度,而是您尝试输入的名称中包含 空格。输入运算符 >>> 在空格上分隔。因此,如果您输入 Half Life 作为名称,输入运算符将只会读取 Half

你可能应该使用 std::getline相反,阅读名称。

至于无限循环,这是因为由于部分名称仍在输入缓冲区中(带有前导空格),因此当您尝试读取菜单项的数字时,输入将失败,将输入保留在缓冲区,你不会检测到它并进入一个无限循环,你想在其中读取一个整数,失败并不断...

使用 std::getline 将解决这两个问题。但是如果你想确保这种情况不会再次发生,你必须在读取菜单选项的整数时添加一些错误检查。这可以简单地类似于

while (!(cin >> choice))
{
// Input of menu alternative failed, ignore input until the end of the line
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

An std::istream::ignore reference .

关于c++ - 超过 8 个字符的字符串会导致无限循环 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44332552/

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