2017-10-21 37 views
-3

我正在使用C++接受一些字的字符串,這些字由任意數量的空格分隔,並打印出每個字的第一個字母。std :: cout會影響編譯的結果嗎?

這裏是我的代碼:

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

int main() { 
    string str = "hi  my name is  rex"; 
    int i = 0; 
    int len = str.length(); 
    while (i < len) { 
     // cout << " blah ";  // <--- Note this line 
     cout << str[i]; 
     while (str[i] != ' ') ++i; 
     while (str[i] == ' ') ++i; 
    } 
} 

如果我運行這段代碼,我會得到一個運行時錯誤(see here)。

但是,如果我取消註釋「blah」行,我將獲得「成功」並打印出(see here)「blah h blah m blah n blah i blah r」。

我知道我應該在這兩個嵌套while循環中檢查我是否有len,但是我想知道爲什麼打印「blah」行對編譯結果有很大的影響。

任何人都可以幫我解決這個問題嗎?謝謝!

+0

什麼是錯誤?將其作爲文本張貼在這裏。 – Carcigenicate

+0

嗨@Carcigenicate,我正在使用一個在線的IDE,並且「運行時錯誤\t#stdin #stdout 0s 15240KB」就是我所得到的。但是由於字符串在主函數內是硬編碼的,可能我不需要任何輸入?對於這兩種嘗試都沒有輸入,但其中一個可行,另一個不可行。 – Rex

+0

在真實環境中運行代碼以獲取有用的錯誤。 – Carcigenicate

回答

1

cout正在使用緩衝區。在清除緩衝區之前,「輸出」保留在緩衝區中 - 內存

但是,到達字符串末尾時,while循環while (str[i] != ' ') ++i;繼續運行。在線IDE給程序一些時間,然後放棄或發生段錯​​誤

相關問題