【问题标题】:c++ text decoder decoding more than asked forc++文本解码器解码超过要求
【发布时间】:2024-01-20 02:25:01
【问题描述】:

我正在开发文本文件解码器和编码器,它们处理两个不同的文本文件。解码器在编码消息下方打印解码消息,但它也打印一堆其他内容。我该如何解决这个问题

#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

如果mmp!nz!obnf!jt!cpc

Dmptfe!

乌夫图乔

解码为

测试123

你好,我叫鲍勃

关闭

测试

这是它也在文本文件中打印的所有额外内容

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

【问题讨论】:

    标签: c++ encryption iostream fstream text-files


    【解决方案1】:

    您看到的额外数据实际上是解码"secret.txt" 中的数据的有效输出。

    我不确定这是否是您想要的,但您是否知道每次运行应用程序时都在读取和写入同一个文件?

    您将越来越多的“解码”数据附加到文件中,因此您会得到您所指的额外输出。


    另外,您的while-loop 存在问题。

    fin.good () 将保持为真,直到在 fin 内部设置了一些错误位,尽管它会进入循环一次太多,因为您应该在调用 @987654325 后立即检查流的状态@。

    目前读取将失败,但您仍将处理“未读”数据。


    std::getline 将返回流对象,并且由于 std::istream(以及 std::ostream)可以隐式转换为布尔值以检查其当前状态,因此您应该将其用作循环条件。

    将您的循环更改为如下所示,看看是否能解决您的问题。

      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
      }
    

    【讨论】:

    • 它仍然给我所有额外的数据
    • @David 再次查看我的帖子,我在处理您的 while 循环时不小心删除了最相关的信息。
    • 不知道还是不行,真是郁闷
    • @David 你读过我的帖子吗?您一遍又一遍地读取/写入 same 文件(“secret.txt”),每次运行程序时都会添加新数据。
    • 是的,我想通了,但我不知道如何阻止它这样做
    【解决方案2】:

    额外的东西不是额外的。您正在将数据写入您正在阅读的同一个文件中,所以您要做的是:

    1. 写一行
    2. 读线

    您正在重新编码已编码的数据。

    【讨论】:

      最近更新 更多