Converting strings to integers
How do I get string thestring
to return theinteger
? I'll be doing it a lot in a script, so I'd like to create a subroutine.
Its quite simple using stringstreams
1 2 3 4 5 6 7 8 9 10
|
#include <sstream>
#include <string>
int convert_to_int (const std::string &str)
{
int x;
std::ostringstream ss(str);
ss >> x;
return x;
}
|
use the function atoi
bare in mind that it is in the cstdlib header and takes a char* argument
So when you pass it your string use the string class method String.c_str();
(or in your case thestring.c_str())
It says that
atoi
was not declared in the scope. I assume I have to include something. So far, I've:
1 2
|
#include <iostream>
#include <string>
|
What do I have to do?
As I said it's in the cstdlib header.
you'll include cstdlib.
Topic archived. No new replies allowed.