文件输入输出输出文件的最后一行重复了无数次

File input output the last line of the output file is repeating infinite more times

本文关键字:文件 一行 输出 输入输出 最后      更新时间:2023-10-16

所以我遇到的问题是,它将最后一行无限次复制到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();
}

我上面关于清除failbiteofbit的评论是不正确的(只有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))在第一次读取错误时中止。