Selfproblemmade Selfproblemmade - 1 month ago 7
C++ Question

for loop decrement doesn't work

Hello I am really new into c++ but programed in JS and PHP before.
I want to reverse the string, the only methods I can use are

length()
and
at()
.

I have already an solution but there is something I want to change but c++ is not actually doing what I want actually.

Actual solution:

getline(cin, user_input);
string inverted_user_input = "";

int user_input_length = user_input.length() - 1;

for (int i = user_input_length; i > -1; i--) {
inverted_user_input += user_input.at(i);
}

cout << "The reverse string is: " << inverted_user_input << endl;


What I want to do:

getline(cin, user_input);
string inverted_user_input = "";

int user_input_length = user_input.length();

for (int i = user_input_length; i > -1; --i) {
inverted_user_input += user_input.at(i);
}

cout << "The reverse string is: " << inverted_user_input << endl;


My first solution work fine but I want to make it looks prettier.

I already know that
length()
begins to count at 1. Thats why I am substract it by 1 on my first code. But I want to use
--i
instead of
i--
to avoid the ugly - 1 like in the first code.

I get a prompt that something exeeds and I checked
i
in first loop but it doesn't decrement. Why?

Answer

In your example --i and i-- do the same thing. You do need to start at length - 1. The difference between i-- and --i is when you're using it in an expression. For example

i = 10;
x = i--;

results in x = 10, i = 9. However, if you did --i instead you'd have x = 9 and i = 9.