Home > Software engineering >  Why this string is not converting to Integer?
Why this string is not converting to Integer?

Time:12-20

I'm trying to convert the string r to an int(num). But it keeps returning 0. Note: When I was returning the string, the answer(reversed number) was correct. My code looks like this:


string n, r = "";
        cin >> n;

        for (int i = n.length(); i >= 0; i--)
        {
            r  = n[i];
        }

        int num;

        istringstream(r) >> num;

        cout << num << endl;

CodePudding user response:

The value of the character n[n.length()] is equal to '\0'

That is when the index of the subscript operator is equal to the size of the string then it "returns a reference to an object of type charT with value charT(), where modifying the object leads to undefined behavior." (The C Standard)

So your reversed string starts with the terminating zero.

Rewrite your for loop the following way

    for ( auto i = n.length(); i != 0;  )
    {
        r  = n[--i];
    }

or

    for ( auto i = n.length(); i != 0; --i )
    {
        r  = n[i - 1];
    }

Of course instead of the for loop you could just write

r.assign( n.rbegin(), n.rend() );

Pay attention to that the initialization of the variable r with an empty string

string n, r = "";

is redundant. You could just write

string n, r;
  • Related