我有以下代碼,由於某種原因,當我嘗試使用for loop
從string wholecommand
申報string attribs
,attribs.length()
返回0
和C++串在for循環使得長度爲0
當我嘗試:
cout<<attribs;
它不輸出任何內容。
for(int q=0;q<wholecommand.length();q++){
cout<<atrribs[q];
}
上面的代碼是我可以得到輸出的唯一方法。我的代碼有什麼問題,以及如何在不使用for循環的情況下輸出數據?
#include<iostream>
#include<string>
using namespace std;
int main(){
string wholecommand="apple";
string atrribs;
for(int a=0;a<wholecommand.length();a++){
atrribs[a]= wholecommand[a];
}
cout<<"Content of Wholecommand: "<<wholecommand<<endl; //returns apple
cout<<"Length of Wholecommand: "<<wholecommand.length()<<endl; //returns 5
cout<<"Content of attributes: "<<atrribs<<endl; ////////contains nothing
cout<<"Length of attributes: "<<atrribs.length()<<endl; ////////returns 0
system("pause");
}
爲什麼不直接分配? 'string attribs = wholecommand;'? – PaulMcKenzie 2014-11-21 04:06:57
如果你想'字符串wholecommand =「蘋果」'複製到'字符串atrribs'那麼你可以這樣做'string stribs = wholecommand;' – Shravan40 2014-11-21 04:10:19