简体   繁体   English

奇怪的文件输出C ++

[英]Strange file output C++

I wanted to print the numbers and put a space between them but just after the compile I noticed I left that + operator in there (C# practice). 我想打印数字并在它们之间加一个空格,但是在编译之后,我注意到我在那儿留下了+运算符(C#练习)。 When I ran this program, it stopped working immediately but there is a very strange output in the text file. 当我运行该程序时,它立即停止工作,但是文本文件中有一个非常奇怪的输出。 Why is the text file like that? 为什么文本文件是这样的?

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

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

Some lines from the 551Kb file: 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

When you add an integer to a string literal, it performs pointer arithmetic. 将整数添加到字符串文字时,它将执行指针算术运算。 So " " + i++ gets the address of the string literal, adds i to it, and increments i . 因此, " " + i++获取字符串文字的地址,将其添加到i ,然后递增i Then it passes the result of the addition to << , so whatever C-style string is at that address gets printed to the file. 然后它将加法的结果传递给<< ,因此该地址处的任何C样式字符串都将被打印到文件中。

Since you're accessing outside the bounds of the string literal's memory, this results in undefined behavior. 由于您正在访问字符串文字的内存范围之外,因此会导致未定义的行为。 So it's writing garbage to the file. 因此,它正在将垃圾写入文件。 It looks like the memory after your string literal contains an internal error message from the runtime library, and you're printing that string. 字符串文字包含运行时库中的内部错误消息后,看起来就像是内存,并且您正在打印该字符串。 Since i gets incremented each time, each iteration starts one character later in the message. 由于i每次都会递增,因此每次迭代都会在消息的后面开始一个字符。

You also have a practically infinite loop because incrementing i won't result in -1 until it overflows and wraps around. 您实际上还有一个无限循环,因为递增i直到溢出并环绕才会产生-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM