[英]c++ array structure issue
Anyone here know C++ or programming in general 这里的任何人都知道C ++或一般的编程
I need help with this program. 我需要有关此程序的帮助。 I made a structure, and an array out of that structure.
我创建了一个结构,并从该结构中创建了一个数组。 When I try entering a name as a string, an infinite loop ensures.
当我尝试输入名称作为字符串时,将确保无限循环。 What is the problem?
问题是什么?
#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;
}
}
}
It seems that you are entering more than one word in data member name using operator >>
. 似乎您在使用
operator >>
输入数据成员名称中的多个单词。 Either enter only one word or use standard function std::getline( std::cin, name )
instead of the operator >>
. 只需输入一个单词,或者使用标准函数
std::getline( std::cin, name )
代替operator >>
。 Do not forget to use member function ignore
before using std::getline
that to remove the new line character from the stream buffer after entering points. 在输入点后,不要忘记使用成员函数
ignore
然后再使用std::getline
从流缓冲区中删除新行字符。
For example 例如
#include <limits>
//...
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
std::getline( std::cin, info[i].name );
Another approach is to use operator >>
as before but to add one more operator that to enter first name and last name. 另一种方法是像以前一样使用
operator >>
,但再添加一个运算符以输入名字和姓氏。 Then you could simply concatenate these two names. 然后,您可以简单地将这两个名称连接在一起。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.