Read file with specifications (SOLVED)-thanks Bazzy

I am trying to read a text file that looks something like this:

0 5 9
0 4 15
1 3 5
2 15 4
11 3 2
15 15 16
end99

The total number of integers before end99 are unknown. But when it gets to end99, the program puts all the individual integers into an array before end99 and then terminates. In the end, the program produces {0,5,9,0,4,15,1,3,5,2,15,4,11,3,2,15,15,16}

I don't know if I should use int, char, or getline to read each value before end99. If I use int, I won't be able to know when I get to end99. If I use char, there will be a problem reading the integers. If I use getline, I don't know how to put the individual integers into an array.

Any ideas would be greatly appreciated. If you are confused about my question, I would be more than happy to clarify.
Last edited on
I'm no expert but you could use a vector class and read ints in a loop. Something like:

1
2
3
4
5
6
vector<int> v;
int a;
ifstream in("data.in"); //say the file is called "data.in"
while(in >> a) {
    v.push_back(a);
}

Last edited on
I can read the numbers from the text using that method, but it doesn't terminate even after reaching end99.
use in.peek() so that:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
char next;
string str;
while(true)
{
   next = in.peek();
   if (isdigit(next))
   {
       in >> a;
       v.push_back(a);
    }
   else if (isalpha(next))
   {
       in >> str;
       if (str=="end99") break;
    }
}

peek() reads the next character of a stream leaving it there
Last edited on
Thanks Bazzy. Your code makes sense. But there's a problem that I can't seem to figure out.
For example, I have a text file that looks like this:

2 10 5
3 9 1
end99

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
char next;
string str;
while(true)
{
   next = in.peek();
   if (isdigit(next))
   {
       in >> a;
       cout << a;
    }
   else if (isalpha(next))
   {
       in >> str;
       if (str=="end99") break;
    }
}


The output I get is 2 and then keeps running without terminating.
Last edited on
that could be for space characters, add a condition for them:
1
2
3
//...
else if(isspace(next))
     in.get();//removes next character from the stream 
Last edited on


Last edited on
Topic archived. No new replies allowed.