此程序除了允许在名字和姓氏之间留出空格外,它的工作原理除外。以下是我所谈论的一个例子:
有人可以帮我解决这个问题吗?我相信它在 string playerName 中,因为它不会接受名字和姓氏之间的空格。
#include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
// Structure to hold the Player Data
struct Player {
string playerName;
int playerNumber;
int pointsScored;
};
// Function Prototypes
void getPlayerInfo(Player &);
void showInfo(Player[], int);
int getTotalPoints(Player[], int);
void showHighest(Player[], int);
int main(int argc, char *argv[])
{
const int N = 12;
Player players[N];
for (int i = 0; i<N; i++) {
cout << "\nPLAYER #" << i + 1 << "\n";
cout << "---------\n";
getPlayerInfo(players[i]);
}
showInfo(players, N);
int totalPoints = getTotalPoints(players, N);
cout << "TOTAL POINTS: " << totalPoints << "\n";
cout << "The player who scored the most points is :";
showHighest(players, N);
cout << "\n";
system("pause");
return 0;
}
void getPlayerInfo(Player &P) {
cout << "Player Name:";
//cin >> P.playerName; **CHANGED THIS**
cin.ignore(std::numeric_limits<std::streamsize>::max(), ' ');
std::getline(std::cin, P.playerName); **TO THIS**
do {
cout << "Player Number:";
cin >> P.playerNumber;
if (P.playerNumber<0)
cout << "invalid Input\n";
} while (P.playerNumber<0);
do {
cout << "Points Scored:";
cin >> P.pointsScored;
if (P.pointsScored<0)
cout << "invalid Input\n";
} while (P.pointsScored<0);
}
void showInfo(Player P[], int N) {
cout << "\nNAME" << "\t\tNUMBER" << "\t\tPOINTS SCORED" << "\n";
for (int i = 0; i<N; i++)
cout << P[i].playerName << "\t\t" << P[i].playerNumber << "\t\t" << P[i].pointsScored << "\n";
}
int getTotalPoints(Player P[], int N) {
int Points = 0;
for (int i = 0; i<N; i++)
Points += (P[i].pointsScored);
return Points;
}
void showHighest(Player P[], int N) {
int HighestPoint = P[0].pointsScored;
string Name = P[0].playerName;
for (int i = 1; i<N; i++) {
if (HighestPoint<P[i].pointsScored) {
HighestPoint = P[i].pointsScored;
Name = P[i].playerName;
}
}
cout << Name;
}
答案 0 :(得分:3)
当std::cin
使用operator>>
插入std::string
时,它会停止在空格(' '
)处读取字符。请改用std::getline
。
std::getline(std::cin, P.playerName); //read everything up to '\n'
答案 1 :(得分:0)
问题在于此代码:
void getPlayerInfo(Player &P) {
cout << "Player Name:";
cin >> P.playerName;//<<----
cin treats&#39; &#39; (空格)作为分隔符。如果你想输入&#39; &#39; (空间)你需要使用:(感谢@James Root)
//before doing get line make sure input buffer is empty
另见:https://stackoverflow.com/a/10553849/3013996
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(std::cin,P.playerName);