在下面的代码中,当我尝试让用户输入他们的名字时遇到错误。我的程序只是跳过它并直接进行函数调用,而不允许用户输入他们的名字。尽管出现错误,我的程序仍在编译。我不确定出了什么问题,因为我是根据在这里找到的其他示例编写该部分的。有什么建议么?
#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);
}
}
}
做完之后cin >> choice;
inside char showMenu()
,如果用户输入1[ENTER]
, the char
消耗 cin 中的 1 个字符,以及换行符stays流内。然后,当程序到达getline(cin, name);
,它注意到里面还有东西cin
,并读取它。这是一个换行符,所以getline
得到它并返回。这就是程序如此运行的原因。
为了修复它 - 添加cin.ignore();
inside char showMenu()
,在您阅读输入后。cin.ignore()
忽略下一个字符 - 在我们的例子中是换行符。
和一句建议——尝试一下not to mix getline
with operator >>
。它们的工作方式略有不同,并且可能会给您带来麻烦!或者,至少记住永远ignore()
当你从那里得到任何东西之后std::cin
。它可能会为您节省很多工作。
这修复了代码:
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)