-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」行對編譯結果有很大的影響。
任何人都可以幫我解決這個問題嗎?謝謝!
什麼是錯誤?將其作爲文本張貼在這裏。 – Carcigenicate
嗨@Carcigenicate,我正在使用一個在線的IDE,並且「運行時錯誤\t#stdin #stdout 0s 15240KB」就是我所得到的。但是由於字符串在主函數內是硬編碼的,可能我不需要任何輸入?對於這兩種嘗試都沒有輸入,但其中一個可行,另一個不可行。 – Rex
在真實環境中運行代碼以獲取有用的錯誤。 – Carcigenicate