2014-02-14 92 views
0

我想知道如何控制字符串並從字符串中獲取字符。
這裏是我的代碼:
用於顯示字符串|的每個字符的循環C++

#include <iostream> 
#include <string> 

using namespace std; 

int mainMenu(); 

int main() { 
    mainMenu(); 
} 

int mainMenu(){ 
    string introText = "Welcome... Let me know your name!"; 
    cout << "\t\t\t"; 
    for (int i = 0; i <= introText.length(); i++){ 
     unsigned controller = i + 1; 
     cout <<introText.substr(i,controller); 
    } 
} 


此輸出如下:

Wellcocomeome..me... e... Le... Let .. Let me. Let me k Let me knoLet me know et me know yot me know your me know your nme know your name know your name! know your name!know your name!now your name!ow your name!w your name! your name!your name!our name!ur name!r name! name!name!ame!me!e!! 


什麼是去朝着正確的方向?我該如何解決這個問題?

+1

爲什麼SUBSTR?爲什麼不使用introText [i]。 – PomfCaster

+0

你能告訴我們你期待的輸出嗎? – michaeltang

+3

也許你對'substr'的​​第二個參數是包含在子字符串中的字符的數量以及* not *上面的索引直到子字符串被採用這一事實感到困惑。 http://www.cplusplus.com/reference/string/string/substr/ – halex

回答

1
#include <iostream> 
#include <string> 

using namespace std; 

int mainMenu(); 

int main() { 
    mainMenu(); 
} 

int mainMenu(){ 
    string introText = "Welcome... Let me know your name!"; 
    cout << "\t\t\t"; 
    for (int i = 0; i < introText.length(); i++){ 
     //unsigned controller = i + 1; 
     //cout <<introText.substr(i,controller); 
     cout << introText[i]; 
    } 
     cout << endl; 
} 

此輸出

   Welcome... Let me know your name! 

只需使用introText[i]

0
int mainMenu(){ 
string introText = "Welcome... Let me know your name!"; 
cout << "\t\t\t"; 
for (int i = 0; i < introText.length(); i++){ 

    cout << introText[i]; 
} 
    cout << endl; 

}