v_head
v_head

Reputation: 815

c++ using getline, output comes with an added space at the beginning

I read data with space using getline, I reverse it. but it gives back a space added. You can see the code below.

#include <iostream>
#include <string>


using namespace std;

int main()
{
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);

    string s;
    getline(cin, s);

    for (int i = s.length(); i >= 0; i--) {
        cout << s[i];
    }

    return 0;
}

When I enter:aaa it gives back: aaa

A space added at first.

How to fix this?

Upvotes: 0

Views: 265

Answers (1)

acraig5075
acraig5075

Reputation: 10756

When i equals the string length then accessing s[i] is undefined behaviour, because it is past the end of the string.

Fix by changing the for loop starting clause.

for (int i = s.length() - 1; i >= 0; i--) {

Upvotes: 4

Related Questions