#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?
CodePudding user response:
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;
}
CodePudding user response:
To avoid indexing errors, use iterators:
for (auto it = std::crbegin(userInput); it != std::crend(userInput); it)
std::cout << *it;
std::cout << '\n';
CodePudding user response:
#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;
}