计数txt文件中的字符,计数错误

Counting characters in txt file giving wrong count

本文关键字:错误 字符 txt 文件 计数      更新时间:2023-10-16

我正在学习C++,现在我已经制作了一个可以进行加密/解密的文件。在我完成所有工作后,我想知道一个文件被压缩/解压缩了多少。所以我决定对输入和输出文件中的字符进行计数,但这是它开始出错的地方。

int get_compression(string file1, string file2){
    string line = "";
    ifstream stream1(file1.c_str());
    double counter1 = 0.0;
    while(getline(stream1, line)){
        counter1 += line.length();
    }
    stream1.close();
    cout << counter1 << "n";
    ifstream stream2(file2.c_str());
    double counter2 = 0.0;
    while(getline(stream2, line)){
        counter2 += line.length();
    }
    stream2.close();
    cout << counter2 << "n";
    return (counter2/counter1)*100;
}

我添加了两个cout语句来查看它统计了什么,但它告诉我,它在实际有528个字符的输入txt文件中统计了496个字符,在有785个字的txt文件中计算了481个字符。我是不是在什么地方犯了新手的错误?

我相信您没有计算新行字符。在Windows上,每行可能出现2个字符的错误。因此,我建议您看看每个文件有多少行,并添加到代码中。

其他答案和注释都非常准确,但您可能想尝试使用Boost文件系统,因为它可以让这样的事情变得更容易。

这是一个示例,摘自http://www.boost.org/doc/libs/1_49_0/libs/filesystem/v3/doc/tutorial.html#Reporting-尺寸

#include <iostream>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;
int main(int argc, char* argv[])
{
  if (argc < 2)
  {
    std::cout << "Usage: tut1 pathn";
    return 1;
  }
  std::cout << argv[1] << " " << file_size(argv[1]) << 'n';
  return 0;
}