Issue
I've got some code that I'm running on Mac OS X that can't be compiled on the Virtual Machine running Linux Mint. This is a simple example. When I run it in Mac, all is fine, but I'm getting issues when I run the same code on Linux, so I'm assuming the library I'm including is not there, but should I be getting an include error then?
Here's the example code that runs on Mac.
#include <iostream>
#include <stdlib.h>
#include <string>
#include <cstdlib>
using namespace std;
int main(){
for (int i = 0; i < 10; i++){
string test = to_string(i);
cout << test << endl;
}
cout << "done" << endl;
return 0;
}
I get no issues here but running on Linux Mint, I get this when I try to compile:
for.cpp: In function 'int main()':
for.cpp:7:28 error: 'to_string' was not declared in this scope
string test = to_string(i);
^
make: *** [for] Error 1
Am I missing something? Any help would be much appreciated!
edit
I realize I forgot to include <string>
on here and I fixed it, but what I changed (<string>
included) still doesn't compile on Linux. I've used to_string
before. I know that much in C++. I also tried adding <cstdlib>
. Once again, this DOES compile on Mac and DOES NOT compile on Linux.
Here is my OSX output:
0
1
2
3
4
5
6
7
8
9
done
Here is my output on Linux Mint (Once again, Virtual Box, g++ make):
test.cpp: In function ‘int main()’:
test.cpp:9:28: error: ‘to_string’ was not declared in this scope
string test = to_string(i);
^
make: *** [test] Error 1
You could reproduce the problem yourself if you don't believe me. It's the same code, you can see for yourself if you want.
Solution
Compile your for.cpp
file like this:
g++ -std=c++11 for.cpp
and run it with:
./a.out
The support for the to_string
function in the <string>
header was added in the C++11 version of the language, so you need to tell GCC to use that version. You can use the c++0x
flag too, for example:
g++ -std=c++0x for.cpp
And you don't have to worry about <cstdlib>
, that has nothing to do with it...
to_string()
is defined in <string>
if you are compiling with C++11 (but is not defined, or unreliably defined as an extension feature, if you are compiling with an earlier version of C++).
Reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string
Answered By - Jahid Answer Checked By - Robin (WPSolving Admin)