奇怪的文件输出 C++

Strange file output C++

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

#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,直到它溢出并回绕。