Abstract
STD: string is library type, and INT and double are built-in type. The two cannot convert each other using the (INT) or (double) method.
Introduction
Use environment: Visual C ++ 9.0/Visual Studio 2008
Method 1:
Use C's atoi () and atof ().
Use c_str () to convert to C string, and then use atoi () and atof ().
String_to_double.cpp/C ++
1 /*
2 (C) oomusou 2008 Http://oomusou.cnblogs.com
3
4 Filename: string_to_double.cpp
5 Compiler: Visual C ++ 9.0/Visual Studio 2008
6 Description: Demo how to convert string to int (double)
7 Release: 08/01/2008 1.0
8 */
9
10 # Include < Iostream >
11 # Include < String >
12 # Include < Cstdlib >
13
14 Using Namespace STD;
15
16 Int Main (){
17 String S = " 123 " ;
18 Double N = Atof (S. c_str ());
19 // Int n = atoi (S. c_str ());
20
21 Cout < N < Endl;
22 }
Method 2:
Use stringstream
Here we use functon template to convert STD: string to int, STD: string to double.
Stringstream_to_double.cpp/C ++
1 /**/ /*
2 (C) oomusou 2006 Http://oomusou.cnblogs.com
3
4 Filename: stringstream_to_double.cpp
5 Compiler: Visual C + + 8.0
6 Description: Demo how to convert string to any type.
7 Release: 11/18/2006
8 */
9 # Include < Iostream >
10 # Include < Sstream >
11 # Include < String >
12
13 Template < Class T >
14 Void Convertfromstring (T & , Const STD :: String & );
15
16 Int Main () {
17 STD :: String S ( " 123 " );
18
19 // Convert STD: string to int
20 Int I = 0 ;
21 Convertfromstring (I, S );
22 STD: cout < I < STD: Endl;
23
24 // Convert STD: string to double
25 Double D = 0 ;
26 Convertfromstring (D, S );
27 STD: cout < D < STD: Endl;
28
29 Return 0 ;
30 }
31
32 Template < Class T >
33 Void Convertfromstring (T & Value, Const STD :: String & S) {
34STD: stringstream SS (s );
35SS>Value;
36}
See also
How to convert int and double to STD: string? (Intermediate) (C ++) (template C ++)
(Original delimiter) how to set int into string? (Initial Release) (C/C ++)
Reference
Bertel Brander, midgaard, http://home20.inet.tele.dk/midgaard/tipc20050107.html