redpix_
redpix_

Reputation: 751

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?

Upvotes: 0

Views: 1153

Answers (3)

Chirag Sutariya
Chirag Sutariya

Reputation: 362

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;

}

Upvotes: 0

herohuyongtao
herohuyongtao

Reputation: 50667

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

Upvotes: 1

Sakthi Kumar
Sakthi Kumar

Reputation: 3045

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

Upvotes: 1

Related Questions