ifstream problems

Below is a code I just tried, which writes to a text file and then attempts to read it back. The output file shows up correctly, but the input stream seems to not be working the way I want. What am I doing wrong with the input stream here?

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main() {
    
    //Fill a simple 2D vector
    vector<vector<int> > vv;
    vector<int> v1, v2;
    
    for (int i=0; i<10; i++) {
        v1.push_back(i);
        v2.push_back(2*i);
    }
    vv.push_back(v1);
    vv.push_back(v2);
    
    //Open an output stream and write values to it
    ofstream out("out.txt");
    if (!out) {
        cout << "Failed to create output stream." << endl;
        cin.get();
        return 0;
    }
    
    out << vv.size(); //size of 2d vector
    for (int i=0; i<vv.size(); i++) {
        out << vv[i].size(); //size of this current 1d vector
        for (int j=0; j<vv[i].size(); j++) {
            out << vv[i][j]; //each integer one-by-one
        }
    }
    out.close();
    
    //Now try to read same file back
    ifstream in("out.txt");
    if (!in) {
        cout << "Failed to create input stream." << endl;
        cin.get();
        return 0;
    }
    
    size_t size2d;
    in >> size2d; //Should be size of 2d vector
    
    cout << "2d vector size: " << size2d << endl;
    cin.get();//pause to look
    
    for (int i=0; i<size2d; i++) {
        
        size_t size1d;
        in >> size1d; //Should be size of next 1d vector
        
        cout << "next 1d vector size: " << size1d << endl;
        cin.get();//pause to look
        
        for (int j=0; j<size1d; j++) {
            int x;
            in >> x; //Get and read back individual values
            cout << x << " ";
            cin.get();
        }
        
        cout << endl;
    
    }
    in.close();
 
    cin.get();
    return 0;
    
}


When I look at the output in a text editor (copied below), I see exactly what I expect - a 2, followed by a 10, followed by 0-9, then another 10, then 0-18. Then the ifstream fails me and says the 2d vector size is zero, and obviously does no further reading as a result.


210012345678910024681012141618

Last edited on
Put spaces between your outputs. The overload of operator>>() can't tell the values apart, otherwise.
Topic archived. No new replies allowed.