![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Programmer
Join Date: Sep 2005
Location: GA
Posts: 99
Rep Power: 3
![]() |
A simple question
I know this might sound like a dumb question, but how do i convert a const char to string;
ex string collect; const char str[] = "convert"; collect = convertostring(str); //what function is available for converting it |
|
|
|
|
|
#2 |
|
Programming Guru
![]() Join Date: Jun 2005
Location: elemental plane
Posts: 1,429
Rep Power: 5
![]() |
#include <iostream>
#include <string>
using namespace std;
int main()
{
string collect;
const char str[] = "convert";
collect = str;
cout << str << endl;
return 0;
}
__________________
"Employ your time in improving yourself by other men's writings, so that you shall gain easily what others have labored hard for." -- Socrates |
|
|
|
|
|
#3 |
|
Programmer
Join Date: Sep 2005
Location: GA
Posts: 99
Rep Power: 3
![]() |
|
|
|
|
|
|
#4 |
|
Programming Guru
![]() Join Date: Jun 2005
Location: elemental plane
Posts: 1,429
Rep Power: 5
![]() |
(atoi)num.c_str()
__________________
"Employ your time in improving yourself by other men's writings, so that you shall gain easily what others have labored hard for." -- Socrates |
|
|
|
|
|
#5 |
|
Programmer
Join Date: Sep 2005
Location: GA
Posts: 99
Rep Power: 3
![]() |
Thanks again ^_^
|
|
|
|
|
|
#6 |
|
Programmer
Join Date: Dec 2005
Posts: 65
Rep Power: 3
![]() |
std::string str = "123"; int i = atoi(str.c_str()); std::string str = "123"; int i; sscanf(str.c_str(), "%i", &i); #include <sstream> ... std::string str = "123"; int i; std::stringstream ss; ss << str; ss >> i; atoi() is probably the easiest. There is also: int atoi(const char *nptr); /* convert string to int */ long atol(const char *nptr); /* convert string to long */ long long atoll(const char *nptr); /* convert string to long long */ |
|
|
|
|
|
#7 |
|
I eat cake for breakfast.
![]() ![]() ![]() ![]() Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9
![]() |
While atoi is easiest for this specific circumstance, using a stringstream, as detailed in para's third example, would be best, as you can do pretty much everything with it:
int i = 41; double d = 2.194; char c = 'x'; std::string s = "meep"; std::stringstream ss; ss << i << ' ' << d << ' ' << c << ' ' << s; std::cout << ss.str(); 41 2.194 x meep |
|
|
|
|
|
#8 |
|
I eat cake for breakfast.
![]() ![]() ![]() ![]() Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9
![]() |
M'kay, I answered a completely different question. Do what para said.
![]() |
|
|
|
|
|
#9 |
|
Hobbyist Programmer
|
lol Ooble not like you to make a mistake
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|