文件输入输出输出文件的最后一行重复了无数次
File input output the last line of the output file is repeating infinite more times
所以我遇到的问题是,它将最后一行无限次复制到numbers2.txt文件中。idk y它像tat一样发生它应该在意识到移动两个字节后停止,这只会导致它到达eof标记
这是代码
#include <iostream>
#include <fstream>
#include<string>
using namespace std;
string conversion(int);
int conversion2(string);
int main()
{
string initialnumber;
fstream sample("numbers.txt", ios::in | ios::out);
ofstream sample2("numbers2.txt");
if (sample && sample2) {
int number2;
string roman;
int number;
char ch;
//cout << ch;
while (!sample.eof()) {
sample.get(ch);
//cout << "OK" << " ";
if (ch != '1' && ch != '2' && ch != '3' && ch != '4' && ch != '5' && ch != '6'
&& ch != '7' && ch != '8' && ch != '9') {
sample.seekg(-1L, ios::cur);
sample >> roman;
sample.seekg(2L, ios::cur);
sample2 << roman << " " << conversion2(roman) << endl;
//cout << conversion2(roman) << " " << roman;
//cout << "OK";
int L = sample.tellp();
cout << L;
} else {
sample.seekg(-1L, ios::cur);
sample >> number2;
sample2 << conversion(number2) << " " << number2 << endl;
sample.seekg(2L, ios::cur);
//int l = sample2.tellp();
//cout << l << " ";
//cout << "OK";
}
}
} else {
cout << "fail";
}
sample.close();
sample2.close();
}
我上面关于清除failbit
和eofbit
的评论是不正确的(只有seekg
的单参数重载会清除eofbit
),但是seekg
会将failbit
设置为错误,而不是eofbit
,所以永远不会满足循环条件。
来自[isream.unformated]
basic_istream<charT,traits>& seekg(off_type off, ios_base::seekdir dir);
效果:表现为未格式化的输入函数(如27.7.2.3第1段所述),只是它不计算提取的字符数,也不影响后续调用gcount()返回的值。构造哨兵对象后,如果失败()!=true,执行rdbuf()->pubseekoff(off,dir,ios_base::in)如果失败,函数会调用setstate(failbit)(可能会抛出ios_base::failure)。
将条件更改为while (!sample.fail())
或更好的while (sample)
,以测试任何流错误,或者while(sample.get(ch))
在第一次读取错误时中止。
相关文章:
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何使代码打印文本文件中的第一行?
- 如何格式化我的文本文件以使其不会一遍又一遍地重复同一行?
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 将字符串存储到文件下一行的变量中
- 为什么这个.c文件只有一行"../xx/xx.c"?
- 比较两个没有一行共同点的大文件
- 如何在c ++中以一行(水平)打印两个文件的数据?如给定的.这两种形式来自两个不同的文本文件
- 到达分隔符时跳到文本文件的下一行
- 从文本文件中读取一行并将其存储在 C++ 中的 2D 矢量中
- 从文本文件中随机选取一行
- 在获取从文件到矢量的每一行之后,数字将被更改或销毁
- 从文件中的一行读取特定数据-C++
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 为什么这一行不输出我的文本文件?
- 如何有效地从文件一行又一行地读取数据(相同类型)到多个向量(vectros的向量)
- 将文件一行的每个元素转换为整数
- 将文本文件一行一行地读入并行数组