我正在研究文本文件解码器和编码器,它们处理两个不同的文本文件。解码器在编码消息下面打印解码消息,但它也会打印一堆其他内容。我该如何解决这个问题
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main() {
ifstream fin; // input file
string line;
ofstream fout;
//open output file
fout.open("secret.txt", ios::app);
if (!fout.good()) throw "I/O error";
// open input file
fin.open("secret.txt");
if (!fin.good()) throw "I/O error";
// read input file, decode, display to console
while (fin.good()) {
getline(fin, line);
for (int i = 0; i < line.length(); i++) // for each char in the string...
line[i]--; // bump the ASCII code down by 1
fout << line << endl; // display on screen
}
// close file
fin.close();
return 0;
}
从编码器读取的文本文件
Uftujoh234
Ifmmp!nz!obnf!jt!cpc
Dmptfe!
Uftujoh
解码为
Testing123
Hello my name is bob
Closed
Testing
这是它在文本文件中打印的所有额外内容
Sdrshmf012
Gdkknlxm`ldhrana
Bknrdc
Sdrshmf
Rcqrgle/01
Fcjjmkwl_kcgq`m`
Ajmqcb
Rcqrgle
Qbpqfkd./0
Ebiiljvk^jbfp_l_
@ilpba
Qbpqfkd
Paopejc-./
Dahhkiuj]iaeo^k^
?hkoa`
Paopejc
O`nodib,-.
C`ggjhti\h`dn]j]
>gjn`_
O`nodib
N_mncha+,-
B_ffigsh[g_cm\i\
=fim_^
N_mncha
M^lmbg`*+,
A^eeh
最佳答案
您看到的额外数据实际上是解码"secret.txt"
中数据的有效输出。
我不确定这是否是您想要的,但您知道每次运行应用程序时都在读取和写入同一个文件吗?
您将向文件附加越来越多的“解码”数据,因此您会得到您所指的额外输出。
此外,您的 while
循环有问题。
fin.good ()
将保持为真,直到在 fin
中设置了一些错误位,尽管它会进入循环一次太多,因为你应在调用 getline (fin, ...)
后立即检查流的状态。
目前读取会失败,但您仍然会处理“未读”数据。
std::getline
将返回流对象,并且由于 std::istream
(以及 std::ostream
)隐式可以转换为 bool 值以检查它的当前状态,您应该将其用作循环条件。
将您的循环更改为如下内容,看看是否能解决您的问题。
while (getline (fin, line))
{
for (int i = 0; i < line.length(); i++) // for each char in the string...
line[i]--; // bump the ASCII code down by 1
fout << line << endl; // display on screen
}
关于c++文本解码器解码超过要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8500676/