简体   繁体   中英

Printing a string in reverse order using stacks and vectors in C++

Quick question: I am trying to accept a string parameter and then print it backwards using stacks and vectors. However, nothing is printed to the screen after it says Here you go!. I believe it has something to do with the vector setup, as I have never worked with this before. Here is the code in question. I would appreciate any help!

void main() {

stack<char> S;
string line;
vector<char> putThingsHere(line.begin(), line.end());
vector<char>::iterator it;

cout << "Insert a string that you want to see backwards!" << endl;
cin >> line;

for(it = putThingsHere.begin(); it != putThingsHere.end(); it++){
    S.push(*it);
}

cout << "Here you go! " << endl; 

while(!S.empty()) {
    cout << S.top();
    S.pop();
}

system("pause");


}

Your vector is being initialized too early, when line is still empty. Move the construction of putThingsHere below the instruction that extracts the string from the standard input:

cin >> line;
vector<char> putThingsHere(line.begin(), line.end());

Here is a live example of your fixed program running correctly.

Notice the use of getline() instead of cin >> line , so that whitespaces in between your characters could still be read as part of one single string.

This said, it is worth mentioning that std::string satisfies the requirements of standard sequence containers and, in particular, has member functions begin() and end() returning an std::string::iterator .

Therefore, you do not need an std::vector<> at all and the snippet below will do the job:

getline(cin, line);
for(std::string::iterator it = line.begin(); it != line.end(); it++) {
    S.push(*it);
}

Your line variable is initially empty. You never really put anything inside the vector PutThingsHere and stack S.

Put the

cout << "Insert a string that you want to see backwards!" << endl;
cin >> line;

before the vector<char> PutThingsHere(...) statement.

First read into line and only then putThingsTHere

stack<char> S;
string line;

cout << "Insert a string that you want to see backwards!" << endl;
cin >> line;
vector<char> putThingsHere(line.begin(), line.end());
vector<char>::iterator it;

我已经在使用std::string了,为什么不使用:

`std::string reversed(line.rend(), line.rbegin());`

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