Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why this string is not converting to Integer?

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;

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading