2014-11-21 69 views
-2

我有以下代碼,由於某種原因,當我嘗試使用for loopstring wholecommand申報string attribsattribs.length()返回0C++串在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"); 
} 
+0

爲什麼不直接分配? 'string attribs = wholecommand;'? – PaulMcKenzie 2014-11-21 04:06:57

+0

如果你想'字符串wholecommand =「蘋果」'複製到'字符串atrribs'那麼你可以這樣做'string stribs = wholecommand;' – Shravan40 2014-11-21 04:10:19

回答

2

將一個

atrribs.resize(wholecommand.length()); 

for()循環之前得到這個工作正常。
您不能通過std::string索引來指定值,其中目標字符串未被調整大小以匹配它們。

雖然這是值得商榷的,但代碼示例的目的是什麼呢?您可以簡單實現與

atrribs = wholecommand; 

沒有那個for()循環。

+0

Works Great !!!對於你的問題:我想要一種方法來分隔命令字符串中的屬性,以便在cmd管道中運行,這是代碼中不起作用的部分。非常感謝 – police123 2014-11-21 04:22:40

1

attribs被構造爲長度爲0的字符串;這就是默認ctor所做的。自然,當你打印一個長度爲0的字符串時,什麼也沒有顯示出來。 (即使你遇到指數超過這個尺寸的元素的問題)。

爲了使它的行爲,確保它足夠長:要麼設置它足夠大的東西(attrib = wholeCommand - 然後你'重做!);或調整它的大小;或者用ctor調用它以使其足夠大(string attrib (5, 'x'); // gives it 5 copies of x)。

正如Paul指出的那樣:你可以可以只是說string attrib = wholeCommand;並完成它。

0

你可以做到以下幾點:

string atrribs(wholecommand.length(), 0); 

從字符串構造的version six,這個字符串構造函數將作爲第一個參數的連續字符數,以填補和作爲第二個參數,以填補什麼字符。在這個例子中,atrribs連續五次填充空字符(0)。在本例中我可以使用任何字符。

+0

Hiya,這可能很好的解決了這個問題......但是如果你能夠編輯你的答案並提供一些關於它是如何以及爲什麼有效的解釋的話,那將會很好:)不要忘記 - 有一堆堆棧溢出的新手,他們可以從你的專業知識中學到一兩件事 - 對你來說顯然對他們來說可能不是這樣。 – 2014-11-21 04:28:26

0

在這個問題的第一個答案中,提出了一個resize()作爲解決方案。

給定代碼模式,假設這是你真正想做的事情,resize()會添加一些浪費的工作。你正在覆蓋attribs中的每個位置。在這種情況下,通過調整字符串大小和默認構建元素來完成的工作是無用的。

attribs.reserve()可能會更好。當然,你不能再使用「[a] =」。