简体   繁体   中英

Reading from file line by line in c++(each line has one string and several int values)?

(the number of integers in each line is the same, but it is unknown)

So I may have a file like this:

title1 34 98 
title2 15 9 
title3 45 15

or

title1 34 98 76 97
title2 15 9 43 8
title3 45 15 34 7

or ...

struct elem
{
  char d[50];
  int v[50];
};

I tried this and it compiles but doesn't work

char ch;
elem col[10];
int num,z=0;

//z-nr of lines, num -nr of int values in the line

ifstream myfile("t2.txt");
if (myfile.is_open())
{
    while (myfile.good())
{
      myfile>>col[z].d;
  num=0;
  myfile.get(ch);
  while(ch!='\n')
  {
        myfile>>col[z].v[num];
    myfile.get(ch);
    num++;
      }
  z++;
}
  myfile.close();
}

the program 'hangs' (the not responding state)

You can try this:

string line;
ifstream myfile("t2.txt");

if (myfile.is_open()) {
    while (getline(myfile, line)) {
        istringstream iss(line);

        iss >> col[z].d;

        int x;
        num = 0;
        while (iss >> x) {
            col[z].v[num] = x;
            num++; 
        }

        z++;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM