我正在使用 C++ 查看 256 个计数并将 ASCII 代表写入文件。
如果我使用生成 256 个字符串的方法然后将该字符串写入文件,则文件重 258 字节。
string fileString = "";
//using the counter to attach the ASCII count to the string.
for(int i = 0; i <= 256; i++)
{
fileString += i;
}
file << fileString;
如果我使用循环写入文件的方法,文件恰好是256bytes。
//using the counter to attach the ASCII count to the string.
for(int i = 0; i <= 256; i++)
{
file << (char)i;
}
这里的字符串是怎么回事,正在将字符串中的哪些额外信息写入文件?
最佳答案
这两个都会创建一个 256 字节的文件:
#include <fstream>
#include <string>
int main(void)
{
std::ofstream file("output.txt", std::ios_base::binary);
std::string fileString;
for(int i = 0; i < 256; i++)
{
fileString += static_cast<char>(i);
}
file << fileString;
}
和:
#include <fstream>
#include <string>
int main(void)
{
std::ofstream file("output.txt", std::ios_base::binary);
std::string fileString;
for (int i = 0; i < 256; ++i)
{
file << static_cast<char>(i);
}
file.close();
}
请注意,在出现差一错误之前,因为没有第 256 个 ASCII 字符,只有 0-255。打印时它将截断为字符。此外,更喜欢 static_cast
。
如果您不以二进制形式打开它们,它将在末尾附加一个换行符。我的标准在输出领域很薄弱,但我知道文本文件应该总是在末尾有一个换行符,它正在为你插入这个。我认为这是实现定义的,因为到目前为止我在标准中所能找到的只是“析构函数可以执行额外的实现定义的操作。”
当然,以二进制方式打开会删除所有栏,让您控制文件的每个细节。
关于Alterlife的顾虑,你可以在字符串中存储0,但是C风格的字符串以0结尾。因此:
#include <cstring>
#include <iostream>
#include <string>
int main(void)
{
std::string result;
result = "apple";
result += static_cast<char>(0);
result += "pear";
std::cout << result.size() << " vs "
<< std::strlen(result.c_str()) << std::endl;
}
将打印两种不同的长度:一种是计数的,一种是空终止的。
关于C++ 将字符串写入文件 = 额外字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1592360/