Read from file until certain number

Something like this, perhaps:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>

bool read_numbers( std::istream& stm, std::vector<int>& vec1, std::vector<int>& vec2 ) {

    const auto old_size = vec1.size() ;

    int first_num ;
    int second_num ;
    while( stm >> first_num && first_num != 0 && stm >> second_num ) {

        vec1.push_back(first_num) ;
        vec2.push_back(second_num) ;
    }

    return vec1.size() > old_size ; // return true if at least one pair was read
}

int main() {

    std::istringstream file(    "1 9\n"
                                "6 2\n"
                                "6 3\n"
                                "-0\n"
                                "3 7\n"
                                "6 7\n"
                                "1 8\n" ) ;

    std::vector<int> column_1 ;
    std::vector<int> column_2 ;

    while( read_numbers( file, column_1, column_2 ) ) {

        std::cout << "column_1: " ;
        for( int v : column_1 ) std::cout << v << ' ' ;
        std::cout << "\ncolumn_2: " ;

        for( int v : column_2 ) std::cout << v << ' ' ;
        std::cout << "\n\n" ;
    }
}

http://coliru.stacked-crooked.com/a/6096b34e52732ad0
Looks like the OP accidentally deleted his or her post. Must be some weird bug! /s

It's okay, I found it:
test1337 wrote:

How would I go about making a loop to read from a file until I reach a -0? I am wanting to store the first line into a vector and the second line into another vector.

Lets say a file is like so,
1 9
6 2
6 3
-0
3 7
6 7
1 8

1
2
3
4
5
6
1
2
3
4
5
6
while(first_num!=-0){
file_name >> first_num;
file_name >> second_num;
vec1.push_back(first_num);
vec2.push_back(second_num);
}


When I do this, it pushes 3 into vec2.
The problem is that you read -0, then you read the next number (3), so you push 0 to vec1 and 3 to vec2, and you exit the while loop on the next iteration. You should check for 0 right after reading the first number.

However, you're treating -0 the same as 0. If you want to stop on -0 specifically, and 0 is considered a valid value, then one possibility would be to use std::getline to read a line, and check if it equals "-0". If so, stop. Else extract the two integers from the line, and push them into your vectors, and read the next line, doing the same checks.
Topic archived. No new replies allowed.