gpt4 book ai didi

c++ - 不管怎样,输入验证都执行 true?

转载 作者:太空宇宙 更新时间:2023-11-04 15:50:04 25 4
gpt4 key购买 nike

好的,这是一个提示用户输入篮球运动员的程序。在提示用户输入播放器名称后,我验证输入以确保它实际上是一个字符串。好吧,无论如何验证总是执行 true 并终止程序。这不会发生在我的其他输入验证中,只是字符串。关于为什么它总是执行正确,从而终止程序的任何想法?谢谢。

这是我的代码:

#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
using namespace std;


//struct of Basketball Player info
struct BasketballPlayerInfo
{
string name; //player name

int playerNum, //player number
pointsScored; //points scored

};

int main()
{
int index, //loop count
total = 0; //hold total points
const int numPlayers = 5; //nuymber of players
BasketballPlayerInfo players[numPlayers]; //Array of players

//ask user for Basketball Player Info
cout << "Enter the name, number, and points scored for each of the 5 players.\n";

for (index = 0; index < numPlayers; index++)
{
//collect player name
cout << " " << endl;
cout << "Enter the name of player # " << (index + 1);
cout << ": ";

//input validation
if((!(getline(cin, players[index].name)))); <----validation goes wrong!
{
cout << "Player Name must be alphabetical characters only!\n";
cout << "Program terminating please start over." << endl;
system("pause");
exit(0);
}

getline(cin, players[index].name);

//collect players number
cout << "Enter the number of player # " << (index + 1);
cout << ": ";

//input validation
if(!(cin >> players[index].playerNum))
{
cout << "Player Name must be numeric characters only!\n";
cout << "Program terminating please start over." << endl;
system("pause");
exit(0);
}
//collect points scored
cout << "Enter points scored for player # " << (index + 1);
cout << ": ";

//input validation
if(!(cin >> players[index].pointsScored))
{
cout << "Player Name must be numeric characters only!\n";
cout << "Program terminating please start over." << endl;
system("pause");
exit(0);
}

cin.ignore();
}

//display
cout << "\n";
cout << "Here is the information for each player: \n";
cout << fixed << showpoint << setprecision(2) << setw(5);
cout << "\n";
cout << " \tName\tNumber\tPoints\n";
cout << "------------------------------------------------" << endl;

for(index = 0; index < numPlayers; index++)
{
cout << "Player # " << (index + 1);
cout << ": \t" << players[index].name << "\t" << players[index].playerNum << "\t" << players[index].pointsScored << endl;
cout << "------------------------------------------------" << endl;

}

//display total points scored by all players
for(index = 0; index < numPlayers; index++)
{
//hold total
total += players[index].pointsScored;
}

cout << "Total Points scored are: " << total << endl;

system("pause");
return 0;

}

最佳答案

你在该行的末尾有一个 ;

关于c++ - 不管怎样,输入验证都执行 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10057868/

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