gpt4 book ai didi

C++ 字符串太大,尾随字符被截断

转载 作者:可可西里 更新时间:2023-11-01 16:30:11 40 4
gpt4 key购买 nike

我正在编写一个程序,该程序在启动时会将预定义的字符串写入文件。该文件的大小约为 5 MB,因此用 5 MB 的十六进制数据填充字符串是一个很大的变量。当我尝试编译它时,我收到一条错误消息,指出字符串太大。 5mb真的那么大吗?我将字符串分成 4 个部分,但每个部分仍然太大。 :/我可以快速轻松地解决这种情况。

注意:我认为自己是一名初级程序员,所以尽量不要越过我的头脑:P

我如何将字符串写入文件的示例:

string file_hex("huge_a**_string_goes_here_or_in_separate_cpp");

ofstream file_out;
file_out.open("tools\\c.exe", ios::binary | ios::trunc);
string res;
res.reserve(file_hex.size() / 2);
for (int i = 0; i < file_hex.size(); i += 2)
{
std::istringstream iss(file_hex.substr(i, 2));
int temp;
iss >> std::hex >> temp;
res += static_cast<char>(temp);
}

file_out << res;
file_out.close();

最佳答案

该标准未指定字符串文字的最大 限制,但建议了最小 大小。来自附件 B - 实现数量

The limits may constrain quantities that include those described below or others. The bracketed number following each quantity is recommended as the minimum for that quantity. However, these quantities are only guidelines and do not determine compliance.

  • Characters in a string literal (after concatenation) [65 536].

然而,标准中的同一部分还规定了以下内容

Because computers are finite, C++ implementations are inevitably limited in the size of the programs they can successfully process. Every implementation shall document those limitations where known. This documentation may cite fixed limits where they exist, say how to compute variable limits as a function of available resources, or say that fixed limits do not exist or are unknown.

可以安全地假设 5MB 的字符串文字将超过编译器施加的最大限制。您应该引用工具链的文档以确定对字符串文字施加的限制。

如果您使用的是 Visual C++ 编译器,则字符串文字的最大大小为 16,384 字节。来自MSDN documentation

The maximum length of a string literal is 16,384 (16K) bytes. This limit applies to strings of type char[] and wchar_t[]. If a string literal consists of parts enclosed in double quotation marks, the preprocessor concatenates the parts into a single string, and for each line concatenated, it adds an extra byte to the total number of bytes.

关于C++ 字符串太大,尾随字符被截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16868362/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com