文件输入输出输出文件的最后一行重复无限次 [英] File input output the last line of the output file is repeating infinite more times
问题描述
所以我的问题是,它将最后一行复制到numbers2.txt文件中无限次。 idb y它发生的事情,它应该停止后实现移动两个字节只是将导致它到达eof标记
So the problem I have is that it copies the last line into the numbers2.txt file infinite number of times. idk y its happening like tat it should stop after realizing moving two bytes over is merely going to result in it reaching the eof marker
这是代码
#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
,因此您的循环条件永远不会得到满足。
My comments above are incorrect about clearing failbit
and eofbit
(only the single parameter overload of seekg
clears eofbit
), seekg
sets failbit
on error however, not eofbit
, so your loop condition is never met.
来自[istream.unformatted]
From [istream.unformatted]
basic_istream<charT,traits>& seekg(off_type off, ios_base::seekdir dir);
效果:作为未格式化的输入函数2.3,第1段),除了它不会计算提取的字符数,并且不影响后续调用gcount()返回的值。在构造sentry对象之后,如果fail()!= true,则执行rdbuf() - > pubseekoff(off,dir,ios_base :: in)。 如果失败,函数调用setstate(failbit)(可能会抛出ios_base :: failure)。
Effects: Behaves as an unformatted input function (as described in 27.7.2.3, paragraph 1), except that it does not count the number of characters extracted and does not affect the value returned by subsequent calls to gcount(). After constructing a sentry object, if fail() != true, executes rdbuf()->pubseekoff(off, dir, ios_base::in). In case of failure, the function calls setstate(failbit) (which may throw ios_base::failure).
将(> sample.fail())更改为或更好
while(sample)
对于任何流错误,或 while(sample.get(ch))
中止第一个读取错误。
Change your condition to while (!sample.fail())
or even better while (sample)
to test for any stream error, or while(sample.get(ch))
to abort on the first read error.
这篇关于文件输入输出输出文件的最后一行重复无限次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!