简体   繁体   中英

For loop for displaying each character of string | C++

I want to know how can I control string and get characters from string.
Here's my code:

#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);
    }
}


This Outputs following:

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


What is the right direction to go toward? How can I solve this?

#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;
}

This outputs

                Welcome... Let me know your name!

Just use introText[i]

std::basic_string::substr is used to extract part of a string. If you want to print each char of the string, you can just use std::basic_string::operator[] or std::basic_string::at :

for (int i = 0; i < introText.length(); i++){
    cout <<introText[i]; // or cout <<introText.at(i);
}
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;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM