gpt4 book ai didi

c++ - 试图将文件读入结构数组,但 for 循环仅显示第一个索引,其余索引为零?

转载 作者:行者123 更新时间:2023-11-28 04:19:02 25 4
gpt4 key购买 nike

我的任务是将文件读入动态结构数组并操作数据。我需要它来显示所有团队名称以及他们的 win=loss 分数,但它似乎只显示第一行。我阅读文件的方式有问题吗?

测试输入文件如下所示:

New England Patriots,3,13,0

Buffalo Bills,15,1,1

Carolina Panthers,9,7,1

Jacksonville Jaguars,10,6,1

Miami Dolphins,7,9,0

Green Bay Packers,11,5,1

San Francisco 49ers,4,12,0


但是我的代码结果是这样的:

Team W-L

New England Patriots 3-0

0-0

0-0

0-0

0-0

0-0

0-0

包括:iostream、fstream、字符串

我的代码:

struct teamInfo
{
string teamName;
int win;
int loss;
int playoffs;
int winlossdiff;
};

void winloss( struct teamInfo *arr, int index)

int main()
{

teamInfo *arr;
char fileName[100];
int choice,size;

ifstream file;

file.clear();
cout<<"Please enter file name:";
cin>>fileName;

while(!fileName)
{
cout<<"Error. Enter valid file name:\n";
cin>>fileName;

}

file.open(fileName);
file>>size;
arr = new teamInfo[size];

for (int i =0; i<size; i++)
{
getline(file,arr[i].teamName,',');
file>>arr[i].win;
file>>arr[i].loss;
cout<<arr[i].loss;
file>>arr[i].playoffs;
{

file.close();

winloss(arr,size);
delete[] arr;

return 0;
}

void winloss( struct teamInfo *arr, int index)
{
cout<<"Team W-L\n";

for(int i=0; i <index; i++)
{
cout<< arr[i].teamName<<" "<<arr[i].win<<"-"<<arr[i].loss<<"\n"<<endl;
}

}



抱歉,如果格式不对,我是新手。

最佳答案

file>>arr[i].win 之后,流中的下一个字符是逗号 ,。下一个操作 file>>arr[i].loss 失败,因为无法将逗号解析为整数的一部分。

关于c++ - 试图将文件读入结构数组,但 for 循环仅显示第一个索引,其余索引为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55886431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com