我寫了下面的代碼中的字符*數組保存並打印以下內容: band1.txt band2.txt ... band3.txt 的代碼似乎是正確的,但什麼是印在控制檯上是很奇怪。如何打印常量字符數組?
代碼:
const char ** current_band = new const char * [103];
stringstream sstm;
string str;
for (i=0;i<103;i++){
current_band[i] = new char[11];
}
for (i=0;i<103;i++){
sstm.str("");
sstm << "band" << i+1 << ".txt";
str = sstm.str();
current_band[i] = str.c_str();
cout << current_band[i] << endl;
cout << i << endl;
}
for (i=0;i<103;i++){
cout << current_band[i] << endl;
cout << i << endl;
}
控制檯:
band1.txt
band2.txt
...
band103.txt
然後最後循環:
band103.txt
band102.txt
band103.txt
band102.txt
...
band102.txt
band103.txt
這怎麼可能?
編輯:其實我想要的「帶」來爲char *爲了調用想要這樣的說法
你應該使用'std :: string'和'std :: vector'來代替C字符串和原始數組。 – crashmstr
該代碼不應編譯。例如,您錯過了'i'的聲明。 – Shoe
_what_可能性如何?你還沒有告訴我們什麼是錯的 –