Looking for way to read Int/Doubles from text file 1 line at a time.

Hey there all.

I'm supposed to write a program that reads ints from a .txt file with multiple lines, and organize them line by line. I made a mistake in reading the assignment, and assumed we were supposed to merge sort the entire program. At the moment, I'm using the following way to read the ints in.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main()
{
    //double
    int i;
    int arraySize=0;
    //double
    int array[9];
    char *inname = "test.txt";
    ifstream infile(inname);

    if (!infile) { //error check on filename
                 errorReadFile(inname);
        system("PAUSE");
        return 0;
    }
    //cout << "Opened " << inname << " for reading." << endl;
    while (infile >> i) { //Need help here! While there is a value, assign it to I.
        cout << i <<", "; //Need a way to determine end of line so I can sort a line at a time.
        array[arraySize] = i;
        arraySize++;  
    }
    
    cout << endl;
    mergeSort( array, 0 , arraySize); //merge sort the array 


I'm using a while loop with the control being "while infile >> i". The only problem is it's grabbing every value in the file until it reaches EOF. This is resulting in it sorting the file instead of sorting each individual line.

To clearly explain, It's supposed to have the following input/output.

When the following is in the input:
5 2 8 9
100 500 300 400

The output is the following.
2 5 8 9
100 300 400 500
(Notice how it sorts each line individually.)

What's the best way to read these lines individually? Is there a way I can set the loop I have to just read one line at a time?
try getline with stringstreams:
1
2
3
4
5
6
string my_string;
getline(infile, my_string);

stringstream my_stream(my_string);
int my_val;
my_stream >> my_val;//repeat until my_stream.eof(); 
Topic archived. No new replies allowed.