STD: String, Int, and double Conversion

Source: Internet
Author: User

STD: string is library type, and INT and double are built-in type.

Method 1: use function template to convert int to STD: string and double to STD: string.

Code

# Include < Iostream >
# Include < Sstream >
# Include < String >

Using NamespaceSTD;

template class T >
void convertfromstring (T & , const STD: string & );

Template<ClassT> 
StringConverttostring (t );

IntMain (){
StringS ("123");
StringS1;

// convert STD :: string to int, double
int I = 0 ;
convertfromstring (I, S);
cout I Endl;

double d = 0 ;
convertfromstring (D, S);
cout d Endl;

// convert int, double to STD :: string
int I1 = 123 ;
S1 = converttostring (I1 );
cout S1 Endl;

DoubleD1= 123.123;
S1=Converttostring (D1 );
Cout<S1<Endl;

// In addition to converting basic types, stringstream also supports conversion of char *.
Stringstream stream;
Char Result [ 8 ];
Int I2 =   8888 ;
Stream < I2; // Insert 8888 to stream
Stream > Result; // Extract values from stream to result
Cout < Result < Endl; // Screen Display "8888"

// When performing multiple conversions, you must call the stringstream member function clear ()
Int Second;
Stream. Clear (); // You must clear the stream before performing multiple conversions.
Stream <   True ; // Insert bool Value
Stream > Second; // Extract int
Cout < Second < Endl;

Return 0;
}

template class T >
void convertfromstring (T & value, const string & S) {
stringstream SS (s );
SS >> value;
}

Template<ClassT> 
StringConverttostring (T value ){
Stringstream SS;
SS<Value;
ReturnSS. STR ();
}

 
Method 2: Convert c_str () into a C string and use atoi () and atof ().

Code

# Include < Iostream >
# Include < String >
# Include < Cstdlib >

Using   Namespace STD;
 
Int Main (){
String S =   " 123 " ;
Double N = Atof (S. c_str ());
// Int n = atoi (S. c_str ());

Cout < N < Endl;
}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.