read text file with specifications

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.
Try to use this code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<iostream.h>      
void x(void)
{
	char m;
	cin >>m;
	if (m != '0')
		x();
		cout << m;
}
int main()
{
	x();
	return 0;
}


I'm not sure this is what you are looking for. The code I gave you lets you enter anything you want, until it reads a 0. Then it would write the things you put backwards.

Maybe you can make a code similar to that, if the idea helped. then perhaps save what you have on your program into a variable and output it in the pattern u want.

Hope my ideas helped you.
Last edited on
I think you should peek a char and act in different ways if it is a digit or it it is a letter. An array is not much good to store an unknown number of elements, I suggest you using STL
http://www.cplusplus.com/forum/articles/6046/
http://www.cplusplus.com/reference/stl/list/
Couldn't you just use a char array to buffer the non-printable characters as well? You could set up a parsing algorithm to print a comma every time one or more consecutive whitespaces are encountered. Here's some pseudocode describing what I would probably do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
ReadTextfile()
{
   // bunch of code here

   bool whitespace_encountered = false;  // flag to indicate if a whitespace is found

   if (current array element is a whitespace && whitespace_encountered == false)
    {
         whitespace_encountered = true;
         InsertCommaInArray();
    }
   if (current array element is a whitespace && whitespace_encountered == true)
         Don'tInsertAnything();
    

   if (current array element is not a whitespace)
   whitespace_encountered = false;  // reset the flag
 
   // continue processing
}
 

Last edited on
Topic archived. No new replies allowed.