0

I have a question. Why my program don't read the last integer if I don't put a space at the end of file? If I have a text file with a only number, without end space, the program don't read anything.

This is my program :

#include <iostream>
#include <fstream>

using namespace std;

int main(){
    fstream f1,f2;
    int k;
    int q;

    cout << "Inserisci numero lettere da leggere : ";
    cin >> q;

    f1.open("in.txt", ios::in);
    f2.open("out.txt", ios::out);

    if(f1.fail()){
        cout << "Impossibile aprire il file";
        exit(1);
    }

    f1 >> k;

    while( !f1.eof() && q > 0){
        q--;
        cout << k << '\n';
        f2 << k;
        f1 >> k;
    }

    f1.close();
    f2.close();

    return 0;
}
Jonas
  • 6,641
  • 8
  • 29
  • 50
Simone Giusso
  • 173
  • 2
  • 2
  • 19
  • You schould write your code in English. – 21koizyd Jul 03 '17 at 20:14
  • Read [Why is iostream::eof inside a loop condition considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – molbdnilo Jul 03 '17 at 20:31
  • Though `!f1.eof()` will lead to writing the last value twice, I actually cannot explain nor reproduce why your program does not read in *any* number. Do you enter a value >0 for `q`? – Stephan Lechner Jul 03 '17 at 20:33

1 Answers1

2

Your program read all the numbers, but you have !f1.eof() check after a read operation. And when there is an end of file after the last number, you never output it.

Replace

f1 >> k;

while( !f1.eof() && q > 0){
    q--;
    cout << k << '\n';
    f2 << k;
    f1 >> k;
}

with

while( f1 >> k && q > 0){
    q--;
    cout << k << '\n';
    f2 << k;
}

And read some articles about input/output via streams.

DAle
  • 8,309
  • 2
  • 24
  • 40