Question

I've been trying for 2 days now to get this code to work. It's just been error after error.

Can anyone point out what i'm doing wrong?

#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;

int main()
{
    int h = 0;
    for(int a = 100; a<1000; a++)
        for(int b = 100; b<1000; b++)
            int c = a * b;
// Error: "c" is undefined
            if ((c == reverse(c)) && (c > h))
                h = c;
    cout << "The answer is: " << h << endl;
}

int reverse (int x)
{
// Error: "'itoa' : function does not take 1 arguments"
    string s = string(itoa(x));
    reverse(s.begin(), s.end());
  return (x);
}

Using std::to_string just gives me more errors as well.

Was it helpful?

Solution

When your compiler explains something to you in an error message, you should believe it. itoa does, in fact, take more than one argument, as you can see at the following link:

http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/

Edit: Oh and this is achievable using standard, C++-style code by the way (fixed a bit of code as per suggestion in the comments):

int reverse(int x)
{
    std::stringstream ss;
    ss << x;

    std::string s = ss.str();
    std::reverse(s.begin(), s.end());

    ss.clear();
    ss.str(s.c_str());

    ss >> x;

    return x;
}

Here. Not sure it's the cleanest solution but it works on my compiler.

Edit: Found out how to use only one stringstream here : How to clear stringstream?

OTHER TIPS

Can I suggest a different solution? Instead of doing int<->string conversions you can test to see if a number is a palindrome this way:

bool is_palindrome(int number, int base = 10)
{
    int rebmun = 0;
    for (int temp = number; temp != 0; temp /= base) {
        rebmun = (rebmun * base) + (temp % base);
    }
    return number == rebmun;
}

Then your test becomes:

if (is_palindrome(c) && (c > h))

For the first problem, correct indentation might make it clear:

int h = 0;
for(int a = 100; a<1000; a++)
    for(int b = 100; b<1000; b++)
        int c = a * b;

if ((c == reverse(c)) && (c > h))
    h = c;

With some extra brackets:

int h = 0;
for(int a = 100; a<1000; a++)
{
    for(int b = 100; b<1000; b++)
    {
        int c = a * b;
        if ((c == reverse(c)) && (c > h))
            h = c;
    }
}

As for the itoa issue, its signature is:

char *  itoa ( int value, char * str, int base );

so you can't just write itoa(x) and expect it to return a string.

There are however better way to convert an int to a string in C++

  • if you have C++11, there std::to_string
  • otherwise, a std::stringstream will do the job.

Like so:

#include <sstream>

int reverse (int x)
{
    std::stringstream ss;
    ss << x;
    string s(ss.str());
    reverse(s.begin(), s.end());
    return (x);
}

Note that this won't return the int reversed though.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top