I'm trying to understand this function. I try to compile an run it, but it gives an error message at line 12. Thanks.

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int stringConvertInt(string raw)
{
int sum=0, power=0;
power=raw.length()-1;
for(int i=0; i<raw.length(); i++)
{
sum=sum+(pow(10,power)*(raw[i]-48));
power--;
}
return sum;
}

int main( )
{
stringConvertInt("Joe");
return 0;
}


Edited by smitsky

4
Contributors
8
Replies
34
Views
3 Years
Discussion Span
Last Post by smitsky

it gives an error message at line 12

What's the error message?

call of overloaded pow(int, int&)' is ambiguous

Then is gives suggestions:

note C:\Dev-Cpp\include\math.h:150 candidates are: double pow(double, double)
note C:\Dev-Cpp\include\math.h:150 long double std::pow(long double, int)
Etc...

In C++ pre-11 you'll need to cast the first argument to a floating point type in order to tell the compiler which overload to use (there are no overloads taking int as the first argument before C++11). Or in this case you could just replace 10 with 10.0 since it's a constant.

In C++11 your code should work as fine.

As well as sepp2k's advice, you're coming across one of the common problems associated with declaring using namespace std;
Remove the namespace and change your function to int stringConvertInt(std::string raw) and then there won't be any ambiguity as to which pow function is to be used.

Thank you. The original code works on another compiler I tried just now, but your solution is good.

nullptr: While I agree that removing using namespace std; and explicitly scoping is a Good Thing, the problem here doesn't seem related to that. Both of the overloads of pow() reside in the std namespace (and in the global namespace as well, in most cases), so that by itself wouldn't affect the resolution issue.

smitsky: Despite what I just said, nullptr's advice is indeed a good idea, and explicit scoping for the standard library functions is a good habit to get into. While it is common and usually convenient to use the standard namespace as a blanket using, especially for new C++ programmers, doing so contains hidden risks. It is better to get into the habit of explicitly scoping functions and objects from std, or at most to scope individual items specifically like so:

using std::cout;
`

This avoids a whole host of complications.

BTW, what version of Dev-C++ are you using? The older and better known Bloodshed original hasn't been updated in close to a decade, so if you are using that version, I would recommend replacing it with the newer Orwell fork, or switch to Code::Blocks. That will get you up to date with the latest version of GCC.

ty +

Thank you both nullptr and Schol-R-LEA.