简体   繁体   中英

Why vector file I/O has this error in c++?

I want to run file I/O. You want to enter int values one by one for vector and output them.

The input goes in properly, but a strange number is output when outputting. Can you help me?

#include <vector>
#include <iostream>
#include <fstream>
using namespace std;

void saveOrder(vector<int> ex)
{
    ofstream fout("ex.txt");
    if (!fout.is_open()) {
        cerr << "fail" << endl;
        return;
    }
    for (vector<int>::iterator it = ex.begin(); it != ex.end(); it++) {
        fout << *it << " ";
    }
}

vector<int> loadOrder()
{
    vector<int> ex2;

    ifstream fin("ex.txt");

    if (!fin.is_open()) {
        cerr << "fail";
        return ex2;
    }

    while (!fin.eof()) {
        cout << fin.get() << endl;
        ex2.push_back(fin.get());
    }

    return ex2;
}

int main() {
    vector<int> ex;

    ex.push_back(1);
    ex.push_back(2);
    ex.push_back(3);
    saveOrder(ex);

    vector<int> ex3;
    ex3 = loadOrder();

    for (vector<int>::iterator it = ex3.begin(); it != ex3.end(); it++) {
        cout << *it << endl;
    }
}

enter image description here

Your loadOrder function implementation is not correct. fin.get() function reads one character at a time and returns it if its available otherwise it returns EOF.

So your while loop reads two character per loop:

cout << fin.get() << endl; display the first character on the console and ex2.push_back(fin.get()); push the next character on to the vector as an integer.

Also it's not a good idea to use fin.eof() in while loop to check for end of file because fin.eof() will returns true only after reading the end of the file. So your while loop will try to access past the end of file before it terminates.

You can change loadOrder function as follows:

vector<int> loadOrder()
{
    vector<int> ex2;

    ifstream fin("ex.txt");

    if (!fin.is_open()) {
        cerr << "fail";
        return ex2;
    }

    int x;
    while (fin >> x) {
        ex2.push_back(x);
    }

    fin.close();
    return ex2;
}

Also if you have access to latest C++ compiler, you can use range-based for loop and automatic type deduction feature to make your code much more simpler.

For example, to print the vector you can use

for(const auto& elem : ex) {
     fout << elem << " ";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM