用于显示字符串|的每个字符的循环C ++

时间:2014-02-14 06:55:46

标签: c++ compilation

我想知道如何控制字符串并从字符串中获取字符。
这是我的代码:

#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!!


走向正确的方向是什么?我该如何解决这个问题?

3 个答案:

答案 0 :(得分: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]

即可

答案 1 :(得分:1)

std::basic_string::substr用于提取字符串的一部分。如果要打印字符串的每个字符,可以使用std::basic_string::operator[]std::basic_string::at

for (int i = 0; i < introText.length(); i++){
    cout <<introText[i]; // or cout <<introText.at(i);
}

答案 2 :(得分: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;

}