c++校验和读取不存在换行符
C++ checksum reading nonexistent newline
我通过将输入文件读入字符数组,然后遍历该数组并将每个字符添加到校验和中,对文件进行非常基本的校验和。问题是,当我这样做时,我所有的校验和都是10太高(10是换行字符的ascii十进制值)。
它是如何换行字符被插入到我的代码,当我知道一个事实,没有换行字符在我的文本?即使是单行文本文件也会添加换行符!
#include <iostream>
#include <fstream>
int main () {
int fileLength = 0;
std::ifstream inputFile;
char charArray[10000];
int checkSumValue = 0;
// open file in binary
inputFile.open("/Path/To/File", std::ios::binary);
// get file length, then return to beginning of file
inputFile.seekg(0, std::ios_base::end);
fileLength = inputFile.tellg();
inputFile.seekg(0, std::ios_base::beg);
// read all data from file into char array
inputFile.read(charArray, fileLength);
// iterate over char array, adding ascii decimal value to checksum
for (int num = 0; num <= fileLength; num++) {
std::cout << "Checksum value before iteration " << num << " is "
<< checkSumValue << std::endl;
checkSumValue += static_cast<int>(charArray[num]);
}
// properly close out the input file
inputFile.close();
inputFile.clear(std::ios_base::goodbit);
std::cout << "The checksum value is: " << checkSumValue << std::endl;
std::cout << "The file length is: " << fileLength << std::endl;
return 0;
}
你的问题在这里:
num <= fileLength
应该是:
num < fileLength
例如。如果长度是1。那么唯一有效的字符是charArray[0]
也注意。这样做:
inputFile.read(charArray, fileLength);
是危险的,因为fileLength
可能大于数组的大小。
一个更好的解决方案是使用一个向量(因为它是动态大小的)
std::vector<char> charArray(fileLength);
inputFile.read(&charArray[0], fileLength);
但是你真的需要将数据复制到数组中吗?为什么不直接做这个加法呢
size_t checkSumValue = std::accumulate(std::istreambuf_iterator<char>(fileLength),
std::istreambuf_iterator<char>(),
size_t(0)
);
Martin也是正确的-你应该(num <</p> 文件长度
另一种可能性是您在编辑器中创建了文件,它人为地为您添加了一个虚假的换行符。这是常见的。尝试将文件转储到十六进制编辑器中。我刚刚运行了你的程序(删除<=),它工作得很好。
相关文章:
- 如何防止clang格式在流运算符调用之间添加换行符<<
- C/C++ - 查询平台相关的换行符(用于内存映射文件)
- 如果有换行符,clang 格式不会附加大括号
- 在 C++ 中的 SetClipboardData() 之后粘贴不包括记事本的换行符
- C++ cout 在擦除换行符后打印字符串不正确
- 程序找不到回车符或换行符。退货超出范围
- 流不追加换行符
- 如何在不添加换行符的情况下将文本附加到QPlainTextEdit,并保持滚动在底部
- 简单的字符串输出不符合预期(出现换行符)
- 除非遇到换行符,否则c++不会写入控制台
- 如何跳过空白但不跳过换行符
- std::cout 不打印带有 endl 的值(换行符说明符)
- 我不想在使用 std::cin 后跳出换行符
- 读取带引号的 CSV 数据,不带换行符作为结束行
- 提升字符串替换不会用字符串替换换行符
- QPushButton工具提示插入一个换行符而不需要我指定它
- c++校验和读取不存在换行符
- 如何在不刷新缓冲区的情况下打印换行符
- 如何在不C++中添加换行符的情况下从控制台读取整数
- 为什么此代码输出文字"n"而不是换行符?