计数txt文件中的字符,计数错误
Counting characters in txt file giving wrong count
我正在学习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;
}
相关文章:
- 我的字符计数代码计算错误.为什么
- 错误:字符数组的初始值设定项太多
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- 在函数 strcpy() 中访问字符数组时出现分段错误
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 为什么我的代码在尝试复制字符数组时引发 C6386 错误?
- 为什么C++在将浮点数转换为字符时没有显示缩小转换错误?
- C++ 字符错误
- 增量生成 - 错误:字符串的第一个字符应'0'或'1'
- 我如何处理有关输入的字符串大小超过字符数组设置大小的错误?
- C++错误字符分配
- C 字符串对象错误字符
- 奇怪的错误字符加密 (ASCII)
- 将 XOR 加密错误字符转换为 int 会失去精度
- 错误:字符数组的初始化器字符串太长c++
- 文件输出中存在错误字符
- 我使用 POCO 解析 JSON.它抛出一个异常:JSON 异常:错误字符.如何处理汉字
- 返回错误字符的c++数组
- c++凯撒密码程序执行错误字符