1

Hello and thank you in advance. This is a very simple question but one that is getting on my nerves. What I want is just to ask for an integer to write to a file and then display every integer. I've learned how to either write to or display from a file and I've been successful at it but when I try to do both at a time it just asks me for the integer and don't display the numbers. I think it may be a problem related to fstream or to the position of the pointer.

Here is the program:

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <fstream>

using std::cout;
using std::cin;
using std::fstream;
using std::endl;

int a;
int x;

int main() {
    fstream in;

    in.open("op.txt", std::ios::app);

    cout << "Write an integer" << endl;
    cin >> x;
    in << " " << x;

    while (in >> a) {
        cout << a << endl;
        cout << in.tellg();
    }

    in.close();
    return 0;

}
Ken White
  • 123,280
  • 14
  • 225
  • 444
Jorge
  • 37
  • 4
  • 1
    Why do you try to write and read at the same time? The way you are doing read and write is sequential, so your guess is correct - it is related to file pointer. You need to do some "random access" to the file, in order to read what you have just written to the file. Check https://stackoverflow.com/questions/14393774/reading-random-access-files – Zlatin Zlatev Aug 23 '17 at 17:59
  • So could I also write first ofstream and ask for the number, then close the file, and open it again with ifstream in order to display the integers? Thanks for answering. – Jorge Aug 24 '17 at 12:22

1 Answers1

1

There are a few things that are need to be fixed:

in.open("op.txt",std::ios::in | std::ios::out | std::ios::app);

here is why you need to do std::ios::in and out

the second problem is when you are switching between writing and reading from the file like you stated the problem is with the position of the read pointer

in.seekg(0, std::ios::beg);//before the while loop;

this sets the read position to 0 so the program can read from the file from the beginning.here

Manvir
  • 769
  • 1
  • 7
  • 15
  • Okay, it finally works, thank you VERY much. I thought that std::ios::in and ::out were already into "fstream", now it works. Thanks. – Jorge Aug 24 '17 at 12:21