C++/SilverLight for Windows Phone , String to integer
Expert: Zlatko - 12/30/2011
QuestionHello,
I am currently working on a project to create a windows phone application on Visual Studio using C++
I am trying to convert a string variable to an integer value.
Im am quite new to C++ and ive tried searching online for solutions
They put the following:
#include <sstream>
#include <string>
using namespace std;
// string to int
string some_string;
istringstream buffer(some_string);
int some_int;
buffer >> some_int;
However for the 1st part #include<sstream> and using namespace std;
I get an error.
Im not sure how to properly do this.
I only know how to reference/import the namespaces but im not sure about the #include
Hope you can help!
Thanks
AnswerHi Cory
You could do this with stringstream if your string has many things and you wish to pick them off individually. If you string has only one integer, then you could use atoi directly on the string. Below is a sample showing both methods. The string is initialized with 2 numbers. Notice that the atoi method can only see the first number.
#include <sstream>
#include <string>
using namespace std;
int main()
{
string some_string = "123 456"; // make sure to initialize the string
istringstream buffer(some_string);
int some_int;
buffer >> some_int; // get first integer
cout << "some_int has " << some_int << endl;
buffer >> some_int; // get second integer
cout << "some_int has " << some_int << endl;
// the atoi method reads characters until it finds one
// which is not a digit, and then stops, so it gets only the integer 123
cout << "using atoi " << atoi(some_string.c_str()) << endl;
}
I tested this on Visual Studio 2003. It should work for that version and newer. Visual Studio 6 does not understand namespaces, but I don't think you are using that.
Best regards
Zlatko