![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Programmer
Join Date: Dec 2004
Location: Ontario, Canada.
Posts: 38
Rep Power: 0
![]() |
Conversion problem. string type to type int.
Alright Ive Used google for like 5 hours now. I know to convert to char * is c_str() but how would I go about changing this type to a int? Any Help Shown appreciated.
|
|
|
|
|
|
#2 |
|
Programming Guru
![]() Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,209
Rep Power: 5
![]() |
I assume you want to convert a string like "42" into the value 42.
In vanilla C, this would be done by; #include <stdlib.h>
int main()
{
const char v[] = "42";
int x;
x = atoi(v);
}#include <string>
#include <cstdlib>
int main()
{
std::string v("42");
int x;
x = std::atoi(v.c_str());
}sscanf() is a C function that reads data from a C-style string in C++, look up the ostringstream class. An example of it's usage follows; #include <string>
#include <sstream>
#include <ostream>
int main()
{
std::string v("42");
std::ostringstream str(v);
int x;
str >> x; // will get value 42
} |
|
|
|
|
|
#3 |
|
Hobbyist Programmer
Join Date: Dec 2005
Posts: 118
Rep Power: 0
![]() |
These string streams look quite interesting. Turns out you want an istringstream though, since that acts as a 'input' from a string, i.e. allows you to read from it.
This runs: #include <string>
#include <sstream>
//#include <ostream>
#include <iostream>
int main()
{
std::string v("42");
std::istringstream str(v);
int x;
str >> x; // will get value 42
std::cout << x << std::endl;
std::cin.sync();
std::cin.get();
} |
|
|
|
|
|
#4 |
|
Programming Guru
![]() Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,209
Rep Power: 5
![]() |
Ah yes, indeed. That's what happens when I rattle off an answer quickly.
|
|
|
|
|
|
#5 |
|
Programmer
Join Date: Dec 2004
Location: Ontario, Canada.
Posts: 38
Rep Power: 0
![]() |
Thanks for the support guys. Appreciated.
|
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|