奇怪的文件输出C ++

时间:2015-10-27 00:08:57

标签: c++ file output ofstream

我想打印数字并在它们之间放一个空格但是在编译之后我注意到我在那里留下了+运算符(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

1 个答案:

答案 0 :(得分:1)

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

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

你也有一个几乎无限循环,因为递增i不会导致-1,直到它溢出并包裹。