c++数组结构问题
c++ array structure issue
这里的任何人都知道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;
相关文章:
- 如何重构类层次结构以避免菱形问题
- 包含矢量指针的结构的内存释放问题
- 在类中返回结构时出现问题
- 我对数据结构、双向链表有一些问题
- C++模板类中结构的编译器问题
- 我的超类中的模板问题与结构定义
- 修改C++结构的特征成员时出现问题
- C++ 结构内部的unordered_map会导致内存泄漏问题吗?
- 指向包含对齐 C 结构C++类的 C 指针的对齐问题
- (ODR 使用问题)在不同文件中priority_queue名称相同的结构
- 在C++中循环访问自定义结构列表的小问题
- 在C++中对结构向量进行排序时出现问题
- 我想直接在结构中插入,但没有一种方法可以正确避免填充问题
- 我的堆栈和库存清单程序的结构有什么问题?
- 将字符数组转换为结构时出现问题. 结构的字符数组变量溢出
- 我应该如何在C++中使用结构体解决输入失败的问题?
- DNS 查询格式标头结构中的小字节序问题
- C++,类结构问题
- 使用初始化列表填充C++中的多维结构数组时出现问题
- 为<vtkDataArray> VTK 非结构化网格声明 vtkSmartPointer 类型的变量时出现问题