我是C++的初學者,我目前正在使用字符串。 我的問題是爲什麼編譯我在下面提供的腳本時,我可以得到字符串的字符,當我使用索引符號,但不能使用cout
獲得字符串本身。 這是代碼:C++:通過索引更改字符串
#include <iostream>
#include <string>
using namespace std;
int main()
{
string original; // original message
string altered; // message with letter-shift
original = "abc";
cout << "Original : " << original << endl; // display the original message
for(int i = 0; i<original.size(); i++)
altered[i] = original[i] + 5;
// display altered message
cout << altered[0] << " " << altered[1] << " " << altered[2] << endl;
cout << "altered : " << altered << endl;
return 0;
}
當我運行此腳本,「改變」的字符串中的字符都正確地與這條線顯示:
cout << altered[0] << " " << altered[1] << " " << altered[2] << endl;
但是字符串本身是不是跟這個顯示行:
cout << "altered : " << altered << endl;
我想知道爲什麼會發生這種情況。
雖然您已經在下面找到了答案,但請嘗試瞭解如何在程序中啓用診斷。您擁有的代碼實際上是錯誤的,但使用C++編譯器提供的診斷模式,可以輕鬆檢測到該錯誤。 –
請現在回答所有答案,並標出最能解答您問題的答案。打開問題並不好:-) –
請注意,C++代碼不是[* scripts *](https://en.wikipedia.org/wiki/Scripting_language),而是*源代碼*。腳本被解釋並且C++源代碼是[編譯](https://en.wikipedia.org/wiki/Compiled_language)。 –