scoots
scoots

Reputation: 294

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


}

Upvotes: 0

Views: 301

Answers (4)

Andy Prowl
Andy Prowl

Reputation: 126442

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

Upvotes: 2

Dan Lecocq
Dan Lecocq

Reputation: 3483

I've your using std::string already, why not use:

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

Upvotes: 0

taocp
taocp

Reputation: 23634

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.

Upvotes: 2

qPCR4vir
qPCR4vir

Reputation: 3571

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;

Upvotes: 0

Related Questions