我試圖將值分配給字串然后訪問它,但對于第一種情況,我沒有得到想要的輸出......
#include <iostream>
#include <string>
using namespace std;
int main(){
string abc;
abc[0] = 'm';
cout << "str1 : " << abc << endl;
cout << "str1 : " << abc[0] << endl;
//-----------------------------------
string xyz;
xyz = "village";
cout << "str2 : " << xyz << endl;
cout << "str2 : " << xyz[0] << endl;
return 0;
}
輸出應該是:
str1 : m
str1 : m
str2 : 村莊
str2 : v
但實際上是:
str1 :
str1 : m
str2 : 村莊
str2 : v
uj5u.com熱心網友回復:
在第一種情況下,您將 -null終止符(每個字串在結尾處用于標記結束)替換為m, 并且可能會導致大量隨機輸出,如果不是SIGSEG崩潰和/或未定義的行為。
解決方案
陣列樣式
std::string myVariable;
// ...
myVariable.resize(3, '\x0');
myVariable[0] = 'm';
myVariable[1] = 'a';
myVariable[2] = 'x';
// And index 3 is already null-terminator (no need to set manually to zero).
你應該怎么做
如果速度不是問題,而您只想要穩定性和易用性,請嘗試以下操作:
abc = 'm';
或者
abc.append(1, 'm');
uj5u.com熱心網友回復:
如下所述,您的程式中存在錯誤。
錯誤
string abc; //this creates a **0 sized** default constructed string object
abc[0] = 'm';// incorrect because you're trying to assign to the 0th index of the string object abc but note that there is no 0th index because the string has 0 size.
注意宣告
abc[0] = 'm';
不正確,因為目前字串物件的abc大小為 0,而您正在嘗試訪問第一個元素(具有第 0 個索引)。但是等等,您如何訪問沒有任何元素的字串的第一個元素(或第 0 個索引),因為它的大小為 0。
解決方案1
而不是分配給0號指數可以追加到字串abc使用
abc = 'm';
解決方案2
您還可以創建std::string具有特定大小(長度)和元素的一個,如下所示:
std::string abc(1, 'm'); //now abc has size(length) of 1 and has the element(0th element) as "m".
有了這個,你不需要使用你正在做的作業。那是你現在不需要 abc[0] = 'm';
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/342689.html
