gpt4 book ai didi

c++ - 获取用户输入的代码不在 C++ 中执行/跳过

转载 作者:行者123 更新时间:2023-11-28 03:04:40 25 4
gpt4 key购买 nike

在下面的代码中,当我试图让用户输入他们的名字时遇到了错误。我的程序只是跳过它并直接进行函数调用,而不允许用户输入他们的名字。尽管有错误,我的程序正在编译。当我根据我在此处找到的其他示例编写该部分时,我不确定出了什么问题。有什么建议么?

#include <iostream>
#include <string>
#include <time.h>

using namespace std;

char showMenu();
void getLottoPicks(int[]);
void genWinNums(int[]);
bool noDuplicates(int[]);

const int SIZE = 7;

int main()
{
int userTicket[SIZE] = {0};
int winningNums[SIZE] = {0};
char choice;
string name;

srand(time(NULL));

do
{
choice = showMenu();

if (choice == '1')
{
cout << "Please enter your name: " << endl;
getline(cin, name);

getLottoPicks(userTicket);
genWinNums(winningNums);

for (int i = 0; i < SIZE; i++)
cout << winningNums[i];
}
} while (choice != 'Q' && choice != 'q');

system("PAUSE");
return 0;
}

添加了 showMenu 的代码:

char showMenu()
{
char choice;

cout << "LITTLETON CITY LOTTO MODEL:" << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "Q) Quit Program" << endl;
cout << "Please make a selection: " << endl;
cin >> choice;

return choice;
}

还有 getLottoPicks(这部分非常错误,我仍在努力):

void getLottoPicks(int numbers[])
{
cout << "Please enter your 7 lotto number picks between 1 and 40: " << endl;

for (int i = 0; i < SIZE; i++)
{
cout << "Selection #" << i + 1 << endl;
cin >> numbers[i];
if (numbers[i] < 1 || numbers[i] > 40)
{
cout << "Please choose a number between 1 and 40: " << endl;
cin >> numbers[i];
}
if (noDuplicates(numbers) == false)
{
do
{
cout << "You already picked this number. Please enter a different number: " << endl;
cin >> numbers[i];
noDuplicates(numbers);
} while (noDuplicates(numbers) == false);
}
}
}

最佳答案

char showMenu() 中执行 cin >> choice; 之后,如果用户输入 1[ENTER] char 从 cin 中消耗 1 个字符,换行符保留在流中。然后,当程序到达 getline(cin, name); 时,它注意到 cin 中仍然有一些东西,并读取它。这是一个换行符,所以 getline 获取它并返回。这就是为什么该程序的行为如此。

为了修复它 - 在读取输入后立即在 char showMenu() 中添加 cin.ignore();cin.ignore() 忽略下一个字符 - 在我们的例子中是换行符。

还有一个建议 - 尝试不要getlineoperator >> 混合使用。它们的工作方式略有不同,可能会给您带来麻烦!或者,至少记住在从 std::cin 中获取任何内容后总是要 ignore()。它可以为您节省大量工作。

这修复了代码:

char showMenu()
{
char choice;

cout << "LITTLETON CITY LOTTO MODEL:" << endl;
cout << "---------------------------" << endl;
cout << "1) Play Lotto" << endl;
cout << "Q) Quit Program" << endl;
cout << "Please make a selection: " << endl;
cin >> choice;
cin.ignore();

return choice;
}

关于c++ - 获取用户输入的代码不在 C++ 中执行/跳过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20027376/

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