2010-09-25 41 views
-1
char * recursivecombo(char *str, int choices, int level) 
{ 
    int len = strlen(str); 

    level++; 
    if(level == choices) 
    { 
      for (int i = 0; i < len -2; i++) 

      { 

        printf("%c", str[i]) ; 
      } 
    } 
    else 
    { 
     for (int i = 0; i < len - 2; i++) 
     { 
       printf("%c",str[i]); 
       recursivecombo(str.substr(1), level); 

     } 
    } 
} 

我想使用字符串而不是char *。如何將此代碼轉換爲使用字符串

+1

什麼是str.substr? – Chubsdad 2010-09-25 06:20:35

+2

如何在char *上執行此str.substr(1)?而且,你不會從這個函數中返回任何東西。在Java中,這是不可編譯的,我不知道C++如何處理這個問題,但我至少會承擔一些錯誤。 – InsertNickHere 2010-09-25 06:20:50

+0

你爲什麼要使用字符串?它比這個代碼更好(更快,更小,可讀,便攜)嗎? – JoshD 2010-09-25 06:22:29

回答

4
std::string recursivecombo(const std::string& str, int choices, int level) 
{ 
    level++; 
    for (int i = 0; i < str.length() -2; ++i) 
    { 
     cout<<str.at(i) ; 
     if(level != choices) 
      recursivecombo(str.substr(1),8,/*Missing choce*/ level); 
    } 
/*Missing return value*/ 
} 

這只是一個使用字符串的模型。與你的函數

1)哪裏是你的返回值

2)如果你打算使用字符串使用COUT,而不是printf的,如果是C++

3)使用前綴++的一些問題。

+0

不錯的使用'at(i)'。注意''i'和'2'將在'i Potatoswatter 2010-09-25 07:53:22

2

正如其他人發佈的,你沒有記錄返回,所以這將是等效代碼:

string recursivecombo(const std::string & str, int choices, int level) 
{ 
    what I wouldn't give for a holocaust cloak 
} 

我想你大概的意思是:

void recursivecombo(const std::string & strInput, int nChoices, int nLevel = 0); 

爲實現:

void recursivecombo(const string & strInput, int nChoices, int nLevel /* = 0 */) 
{ 
    nLevel++; 
    if(nLevel == nChoices) cout << strInput.substr(0,strInput.length()-2); 
    else 
    { 
     for (int i = 0; i < str.length() - 2; i++) 
     { 
      cout << str.at(i); 
      recursivecombo(str.substr(1), nChoice, nLevel); 
     } 
    } 
} 
相關問題