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

Program that reads and writes integers to a file

本文关键字:整数 程序 文件 读取      更新时间:2023-10-16

您好,提前感谢您。这是一个非常简单的问题,但却让我感到紧张。我想要的只是要求一个整数写入文件,然后显示每个整数。我已经学会了如何写入文件或从文件显示文件,并且我已经成功了,但是当我尝试一次同时执行这两项操作时,它只是要求我输入整数而不显示数字。 我认为这可能是与流或指针位置有关的问题。

这是程序:

#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

相关文章: