1

我正在使用 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;

如果我使用循环写入文件的方法,该文件正好是 256 字节。

//using the counter to attach the ASCII count to the string.
for(int i = 0; i <= 256; i++)
{
    file << (char)i;
}

字符串在这里发生了什么,字符串中的哪些额外信息被写入文件?

4

2 回答 2

6

这两个都创建了一个 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;
}

将打印两种不同的长度:一种是计数的,一种是空终止的。

于 2009-10-20T04:19:44.987 回答
0

我对 c++ 不太熟悉,但您是否尝试使用 null 或 '/0' 初始化文件字符串变量?也许然后它会给出256字节的文件..

N 是的循环应该 < 256

PS:我真的不确定,但我想它值得一试..

于 2009-10-20T04:20:48.917 回答