gpt4 book ai didi

c++ - 奇怪的文件输出 C++

转载 作者:行者123 更新时间:2023-11-28 06:00:34 24 4
gpt4 key购买 nike

我想打印数字并在它们之间放置一个空格,但就在编译之后我注意到我把 + 运算符留在了那里(C# 实践)。当我运行这个程序时,它立即停止工作,但文本文件中有一个非常奇怪的输出。为什么文本文件是这样的?

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
int i=0;
ofstream f("out.txt");
while(i != -1)
{
f << " " + i++;
}
return 0;
}

551Kb 文件中的一些行:

deleted virtual method called
eleted virtual method called
leted virtual method called
eted virtual method called
ted virtual method called
ed virtual method called
d virtual method called
virtual method called
virtual method called
irtual method called
rtual method called
tual method called
ual method called
al method called
l method called
method called
method called
ethod called
thod called
hod called
od called
d called
called
called
alled
lled
led
ed
d

最佳答案

当您将整数添加到字符串文字时,它会执行指针运算。所以" " + i++获取字符串文字的地址,添加 i并递增 i .然后它将加法的结果传递给<<。 , 因此该地址处的任何 C 风格字符串都会打印到文件中。

由于您正在访问字符串文字内存的边界之外,这会导致未定义的行为。所以它正在向文件写入垃圾。看起来您的字符串文字包含来自运行时库的内部错误消息之后的内存,并且您正在打印该字符串。自 i每次都会递增,每次迭代都会在消息后面的一个字符开始。

您还有一个几乎无限的循环,因为递增 i不会导致 -1直到它溢出并环绕。

关于c++ - 奇怪的文件输出 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33357788/

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