将整数读取和写入文件的程序

Program that reads and writes integers to a file

您好,提前谢谢您。这是一个非常简单的问题,但却让我很紧张。我想要的只是要求一个整数写入文件,然后显示每个整数。我已经学会了如何写入文件或从文件中显示,并且我在这方面取得了成功,但是当我尝试同时执行这两项操作时,它只要求我输入整数而不显示数字。 我觉得可能是fstream的问题,或者是指针位置的问题。

程序如下:

#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;

}

有几件事需要解决:

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

就是为什么你需要做 std::ios::in and out

第二个问题是当您像您所说的那样在写入和读取文件之间切换时,问题出在读取指针的位置

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

这会将读取位置设置为 0,以便程序可以从文件的开头读取。here