向文件读取和写入整数的程序
Program that reads and writes integers to a file
您好,提前感谢您。这是一个非常简单的问题,但却让我感到紧张。我想要的只是要求一个整数写入文件,然后显示每个整数。我已经学会了如何写入文件或从文件显示文件,并且我已经成功了,但是当我尝试一次同时执行这两项操作时,它只是要求我输入整数而不显示数字。 我认为这可能是与流或指针位置有关的问题。
这是程序:
#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
相关文章:
- 内联程序集printf将整数解释为地址
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 如何将字符串和整数读取到两个单独的动态数组中的程序编写?
- 我正在尝试制作一个程序,在添加 n 天(整数)后告诉一个人什么是一天(例如星期一等)
- 编写一个读取五个整数并执行一些任务的C++程序
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- 16 位系统中的程序如何访问大于 65535 的整数,但不能访问地址
- 我需要编写一个程序来读取一个文件,该文件将输出所有唯一的整数,如果已经看到整数,它将被关闭
- 编写一个程序,提示用户输入一个整数,然后输出数字的单个数字和数字的总和
- 在控制台上输出我从文件中读取的整数,将程序插入无限循环
- 向文件读取和写入整数的程序
- MongoDB C++ 驱动程序 - 8 位和 16 位整数?
- 编写一个程序,输入整数 n 并打印该数字的字符数(符号除外)
- 我的程序不断四舍五入到最接近的整数
- 为什么在此C++程序上添加负整数会导致正整数?
- 调用 Parse int 函数时编译 parse 整数程序时出现问题
- C++程序,将整数输入转换为字符的问题
- 我的C++程序有问题.涉及动态调整整数数组的大小
- 程序终止,而不是继续整数输入验证循环
- 查找混合整数程序的绑定约束