读取文件时出现分段错误

时间:2019-04-30 18:00:17

标签: c++

所以我的问题是我在for循环中做了i <= size。我将其更改为i <大小。没有更多细分错误!但是当我运行它时,我的结果仍然显示为0-0,并且也不显示团队名称。我如何读取文件时出现问题吗?

我的任务是从文件中读取数据,将其读取到动态结构数组中并进行显示/操作。但是我继续遇到这个结果:

Please enter file name:testfile.txt
Team W-L
 0-0
 0-0
 0-0
 0-0
 0-0
 0-0
 0-0

我不知道如何解决它。我的测试文件如下所示:

7
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

这是我的代码:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

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


void winloss( struct teamInfo *arr, int index);


int main()
{

        teamInfo *arr=0;
        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;
                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<<endl;
}

}

1 个答案:

答案 0 :(得分:0)

ifstream file上调用“ >>”运算符时,它将读取整个文件。一次调用“ >>”后,对“ >>”或“ getline”的后续调用将没有任何数据流。

对此的一种解决方法是使用getline而不是“ >>”。例如:

  string tmp;
  getline(file, tmp);
  size = atoi(tmp.c_str());

  arr = new teamInfo[size];

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

除了从“ >>”更改为getline之外,我们还必须进行其他两项更改:

  1. 使用名为tmp的字符串保存下一个令牌。然后将其转换为大小,赢,输和季后赛的整数。
  2. 每当我们只想读一个“,”而不是读到行尾时,就向getline添加参数','。
相关问题