2015-10-27 104 views
0

我想打印數字並在它們之間放置一個空格,但在編譯後我發現我留下了那個+運算符(C#練習)。當我運行這個程序時,它立即停止工作,但文本文件中有一個非常奇怪的輸出。爲什麼這樣的文本文件?奇怪的文件輸出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

當您添加到一個字符串一個整數,它執行指針運算。因此" " + i++獲取字符串文字的地址,向其添加i,並遞增i。然後它將加法的結果傳遞給<<,因此無論該C地址字符串是在該地址打印到文件。

由於您正在訪問字符串文字內存的邊界之外,因此導致了未定義的行爲。所以它正在向文件寫入垃圾。它看起來像你的字符串文字包含來自運行時庫的內部錯誤消息之後的內存,並且正在打印該字符串。由於每次都會增加i,每次迭代都會在消息的後面開始一個字符。

你也有一個實際上無限循環,因爲增加i不會導致-1,直到它溢出並回繞。

+0

整數溢出會導致未定義的行爲,因此它可能永遠不會導致-1。例如,編譯器可以優化該測試。 –