2

(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)

Natasha
  • 1,470
  • 5
  • 18
  • 24
  • In what way does it not work? I can see that you have a potential buffer overflows but I suspect that this isn't what you talk about... – Dietmar Kühl Oct 27 '12 at 19:16
  • 1
    possible duplicate of [C++: Read file line by line](http://stackoverflow.com/questions/7868936/c-read-file-line-by-line) – jww Apr 05 '14 at 17:49

1 Answers1

5

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++;
    }
}
Murilo Vasconcelos
  • 4,677
  • 24
  • 27
  • thank you a lot, it does work, but there is this problem: I'm doing an MFC application project(using the values from the text file as input) and after I execute it it's all right, but if I resize the output window ,z(the nr of lines, increases with each resize , so it's 3,6,9...) – Natasha Oct 27 '12 at 21:10