Devesh Agrawal
Devesh Agrawal

Reputation: 9212

Compilation error while using to_string in c++ program

To get precision and scale of a number i am using this simple program. But while converting number into string it is giving compilation error.

g++ precision.cpp
precision.cpp: In function ‘int main()’:
precision.cpp:6: error: ‘to_string’ was not declared in this scope

When I compile with the -std=c++0x switch I get

g++ precision.cpp  -std=c++0x
precision.cpp: In function ‘int main()’:
precision.cpp:6: error: call of overloaded ‘to_string(int)’ is ambiguous
/usr/lib/gcc/i686-redhat-linux/4.4.4/../../../../include/c++/4.4.4/bits/basic_string.h:2604: note: candidates are: std::string std::to_string(long long int)
/usr/lib/gcc/i686-redhat-linux/4.4.4/../../../../include/c++/4.4.4/bits/basic_string.h:2610: note:                 std::string std::to_string(long long unsigned int)
/usr/lib/gcc/i686-redhat-linux/4.4.4/../../../../include/c++/4.4.4/bits/basic_string.h:2616: note:                 std::string std::to_string(long double)

The source code looks like this:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    string value = to_string(static_cast<int>(1234));
    int precision = value.length();
    int scale = value.length()-value.find('.')-1;
    cout << precision << " " << scale;
    return 0;
}

What is causing this error?

Upvotes: 0

Views: 3459

Answers (2)

Javier Castellanos
Javier Castellanos

Reputation: 9864

I recommend to use boost::lexical_cast instead.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409136

The first error is because std::to_string is a C++11 feature, and GCC by default compiles in C++03 mode.

The second error, when you are using the correct flag, is probably because the support for C++11 in GCC 4.4 (which you seem to be using) is quite minimal. As you can see by the error messages, the compiler shows you the alternatives it have.

By the way, you don't need to cast integer literals to int, they are of type int by default. You might want to cast it to long double though, as that's one of the valid overloads and you seems to want to find the decimal point (the code will not work as expected if there is no decimal point in the string, like when converting an integer).

Upvotes: 3

Related Questions