c++数组结构问题

c++ array structure issue

本文关键字:问题 结构 数组 c++      更新时间:2023-10-16

这里的任何人都知道C++或一般编程

我需要这个项目的帮助。我做了一个结构,用这个结构做了一组数组。当我尝试将名称作为字符串输入时,会有一个无限循环。问题出在哪里?

    #include <iostream>
    #include <string>
    const int size = 12;
    struct soccer
    {
        std::string name;
    float points, jersey;   
};

void input(soccer []);
int main()
{
    soccer info[size];
    float total;
    input(info);
}
void input(soccer info [])
{
    for (int i = 0 ; i < size ; i++)
    {
        std::cout << "Enter the name of soccer player #" << i+1 << ": ";
        std::cin >> info[i].name;
        std::cout << "Enter the jersey number for this player:";
        std::cin >> info[i].jersey;
        while (info[i].jersey < 0)
        {
            std::cout << "The jersey number cannot be a negative number. Please enter a value number for jersey: ";
            std::cin >> info[i].jersey;
        }
        std::cout << "Enter the number of points scored by this player: ";
        std::cin >> info[i].points;
        while (info[i].points < 0)
        {       
            std::cout << "Points scored cannot be a negative number. Please enter a valid number for points: ";
            std::cin >> info[i].points;
        }
    }
}

似乎使用operator >>在数据成员名称中输入了多个单词。只输入一个单词,或者使用标准函数std::getline( std::cin, name )而不是operator >>。在使用std::getline之前,不要忘记使用成员函数ignore,该函数用于在输入点后从流缓冲区中删除新行字符。

例如

#include <limits>
//...
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), 'n' ); 
std::getline( std::cin, info[i].name );

另一种方法是像以前一样使用operator >>,但增加了一个用于输入名字和姓氏的运算符。然后您可以简单地将这两个名称连接起来。

std::string first_name;
std::string last_name;
//...
std::cout << "Enter the first name of soccer player #" << i+1 << ": ";
std::cin >> first_name;
std::cout << "Enter the last name of soccer player #" << i+1 << ": ";
std::cin >> last_name;
info[i].name = first_name + " " + last_name;