0

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?

v_head
  • 759
  • 4
  • 13
  • About [using namespace std](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)... And you shouldn't abuse your standard IO streams for file IO, use file streams instead: `std::ifstream in("input.txt"); if(in) { std::ofstream out("output.txt"); if(out) { /* now use in/out instead of std::cin/std::cout */ } }` (you need `` header for). – Aconcagua Oct 15 '19 at 07:49
  • Actually, there's a better way to do: `for(auto i = s.rbegin(); i != s.rend(); ++i) { std::cout << *i; }` – in general, it is usually preferrable to use iterators instead of indices – unless you explicitly need the indices for yet *another* purpose. – Aconcagua Oct 15 '19 at 08:16
  • You could alternatively fall back to standard algorithm library (*if* you are allowed to): `std::reverse(s.begin(), s.end()); std::cout << s;` – Aconcagua Oct 15 '19 at 08:19

1 Answers1

4

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--) {
acraig5075
  • 10,588
  • 3
  • 31
  • 50