in my program, i put the user enters into a string, then i need to get some information out of the string and store it into a char or double. would anyone give me some help ? THX :cool:
Printable View
in my program, i put the user enters into a string, then i need to get some information out of the string and store it into a char or double. would anyone give me some help ? THX :cool:
you need to specify what type of string you are using.
For "simple" null terminated char arrays use atoi()
if cString is a char[] and myInt is an int
myInt = atoi(cString);
For instances of the STL string class use the c_str() method in addition to atoi();
myInt = atoi(stlString.c_str());
Some other string classes have methods that facilitate the conversion
i used this:
how can i pass value in these variable ? :confused:Code:#include<string>
string a;
double b;
char c;
as he said up there by using c_str() function with the stl string class.
Since atoi only takes input of older character arrays for strings you have to use the function c_str() to convert a stl string to one. That code puts "123456789" into string a and then using atoi() puts it as a variable into int b.Code:#include <iostream>
#include <stdlib.h>
using namespace std;
int main(int argc, char *argv[])
{
string a;
int b;
a = "123456789";
b = atoi(a.c_str());
/* b now equals 123456789 */
cout<<b;
system("PAUSE");
return 0;
}
And the C++ way...
ggCode:#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
string a = "123.456 Z";
double d;
char c;
istringstream istream(a);
istream >> d >> c;
cout << "d = " << d << endl;
cout << "c = " << c << endl;
return 0;
}//main
thank you for your help, now i have solved my problem. :D :D :D