0
#include <iostream>
using namespace std;
int main() {

int i;
string userInput;
int index;

getline(cin, userInput);

index = userInput.length();

for(i = index; i <= 0; i--) {

cout << userInput.at(i);

}

return 0;
}

Program is generating absolutely 0 output. No errors or bugs, I just can't generate any output... Any ideas to why?

0

3 Answers 3

4

You got the loop condition wrong

Try i >= 0 (instead of <= )

In addition, you'll want to start the index at index-1

Working example:

#include <iostream>
using namespace std;
int main() {

    int i;
    string userInput;
    int index;

    getline(cin, userInput);

    index = userInput.length();

    for(i = index-1; i >= 0; i--) {
        cout << userInput.at(i);
    }

    return 0;
}
Sign up to request clarification or add additional context in comments.

4 Comments

I changed the loop condition to that and now I'm getting this error "terminate called after throwing an instance of 'std::out_of_range'
Thanks, that worked. Why would it give me an error if it was just outputting i at the max length... isn't that equal to some character value? Thank you for the help.
In C, potentially, and it would be dangerous, but with std::string, no. Reference: cplusplus.com/reference/string/string/at (The function automatically checks whether pos is the valid position of a character in the string (i.e., whether pos is less than the string length), throwing an out_of_range exception if it is not.)
Note that since the loop itself is already ensuring the index does not go out of bounds of the string, using at() to perform the same bounds checking is redundant. You can use operator[] instead: for(i = index-1; i >= 0; i--) { cout << userInput[i]; }
2

To avoid indexing errors, use iterators:

for (auto it = std::crbegin(userInput); it != std::crend(userInput); ++it)
    std::cout << *it;
std::cout << '\n';

1 Comment

Or range based for loop
0
#include <iostream>
#include <algorithm> //for std::reverse

int main() {

  std::string userInput;

  std::getline(std::cin, userInput);

  //Print Reverse with for
  for(int i = userInput.length()-1; i >= 0; i--) {
    std::cout << userInput.at(i);
  }

  std::cout<<std::endl;

  //Reverse userInput variable content and print
  std::reverse(userInput.begin(),userInput.end());
  std::cout<< userInput;

  return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.