0

C++ conversion

How would you convert an int to string in C++? /******************************************************************************************************\ Edit: itoa worked but it made the numbers be in a char array, i wanted it to be a string, to fit my project(Getting a squared number, turning into a string to get the middle numbers then turning these middle numbers into an int and so on), if anyone came here to see the answer and have the same problem, use: #include <sstream> //We need this lib using namespace std; //So we dont use std:: int i = 12; //Any int value, can be double(I think) ostringstream buffer; //we need sstream for this buffer << i; //put the number in the var string numString= buffer.str(); //conversion happens here

26th Jan 2017, 11:59 AM
Dawzy
Dawzy - avatar
10 Respuestas
+ 7
On desktop compilers, you may use itoa() function.
26th Jan 2017, 12:40 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
int variable = 5; std::string foo = std::to_string(variable); en.cppreference.com/w/cpp/string/basic_string/to_string
25th Jan 2017, 10:41 PM
Jakub Stasiak
Jakub Stasiak - avatar
+ 1
I got it to work with the itoa, but if you are planning to use itoa() function, don't use it on this website's compiler, it doesn't work on here for some reason.
26th Jan 2017, 10:58 AM
Dawzy
Dawzy - avatar
0
the only way I know is what is called "type casting". I only used it once or twice, but it's pretty well documented online
25th Jan 2017, 9:44 PM
Ethan
0
I can't remember what language it belongs to, but I know there is also a function called "stringify", I'm just not sure if that was in c++ or not
25th Jan 2017, 9:45 PM
Ethan
0
Could you provide me a link or an example so I can look at it myself?
25th Jan 2017, 9:45 PM
Dawzy
Dawzy - avatar
0
I found an even easier way, cplusplus.com states that there are functions provided to do specifically what you need to do in the string library. http://www.cplusplus.com/articles/D9j2Nwbp/
25th Jan 2017, 9:52 PM
Ethan
0
I tried the first example as it seemed the easiest and less confusing, but I get this error: ..\Playground\:10:15: error: aggregate 'std::ostringstream convert' has incomplete type and cannot be defined ostringstream convert;
25th Jan 2017, 10:01 PM
Dawzy
Dawzy - avatar
0
Did you import the string library?
25th Jan 2017, 10:02 PM
Ethan
0
@Jakub Stasiak Error: to_string is not a member of std Error2: to_string was not declared in this scope @Ethan Yes, I did import the string lib
26th Jan 2017, 10:33 AM
Dawzy
Dawzy - avatar