0

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

yujeong
  • 1
  • 1
  • 2
    [`fin.get()` returns a character per call](https://en.cppreference.com/w/cpp/io/basic_istream/get), which is not what you want. Do `int x; fin >> x;` to read integers. – kotatsuyaki Jun 06 '22 at 05:52
  • 1
    See prev reply and you're calling fin.get() twice once to output to screen and once to put push_back. This is also not what you want. – Pepijn Kramer Jun 06 '22 at 05:56
  • Also read [Why is `iostream::eof()` inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Ted Lyngmo Jun 06 '22 at 05:57

1 Answers1

-1

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 << " ";
}
Aamir
  • 1,974
  • 1
  • 14
  • 18