计算txt文件中的字符给出错误的计数

时间:2013-12-13 21:44:43

标签: c++ counter

我正在学习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语句来查看它的计数,但是它告诉我它在输入txt文件中计算了496个字符,真正有528个字符,txt文件中有481个字符有785个字符。我在某处犯了一个菜鸟错误吗?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

其他答案和评论非常准确,但您可能想尝试使用Boost Filesystem,因为它使这样的事情变得如此简单。

这是从http://www.boost.org/doc/libs/1_49_0/libs/filesystem/v3/doc/tutorial.html#Reporting-size

的提升文档中获取的示例
#include <iostream>
#include <boost/filesystem.hpp>
using namespace boost::filesystem;

int main(int argc, char* argv[])
{
  if (argc < 2)
  {
    std::cout << "Usage: tut1 path\n";
    return 1;
  }
  std::cout << argv[1] << " " << file_size(argv[1]) << '\n';
  return 0;
}
相关问题