c++ - 带字符间距的字符串

标签 c++

除了名字和姓氏之间不允许有空格外,该程序可以正常工作。下面是关于我正在谈论的内容的示例:

Link to Picture

有人可以帮我解决这个问题吗?我相信它在 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;
}

最佳答案

std::cin 使用 operator>> 插入到 std::string 时,它会在空格处停止读取(' ') 个字符。请改用 std::getline

std::getline(std::cin, P.playerName); //read everything up to '\n'

关于c++ - 带字符间距的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33860929/

相关文章:

c++ - 网格表示 - 一个顶点(空间位置)= 一个位置,tex 坐标,法线?

使用模板的 C++ 静态分派(dispatch)

c++ - CMakeLists.txt 中的 GLM 链接

c++ - 对对 vector 的特定位置进行排序

c++ - 在模板中调用对象的方法

c++ - 如何使用 sprintf 将 uint_64 类型的数组附加到 char 数组?

C++ 头文件 (.h) 或 C 中的 .h 文件包含滤波器系数

C++ rapidjson 返回值

c++ - 如果由另一个 OpenMP 程序调用,则外部调用的 OpenMP 程序仅使用一个线程运行

c++ - 在 OpenCV 中通过 cartToPolar 放置点 vector