C + + Converts a string type to int, float, and double type mainly in the following ways:
# method One: Use StringStream
StringStream has been introduced in methods that convert int or float types to string types, and can also be used as a type of string to convert to a commonly used numeric type.
Demo:
[CPP]View Plaincopy
- #include <iostream>
- #include <sstream>//use StringStream to introduce this header file
- Using namespace std;
- Template functions: Converting a string variable to a common numeric type (this method is universally applicable)
- Template <class type>
- Type stringtonum (const string& str)
- {
- Istringstream ISS (str);
- Type num;
- ISS >> num;
- return num;
- }
- int main (int argc, char* argv[])
- {
- String str ("00801");
- cout << stringtonum<int> (str) << Endl;
- System ("pause");
- return 0;
- }
Output Result:
801 Please press any key to continue ... |
#方法二: Use the Atoi (), Atil (), atof () functions-----------------are actually conversions of char types to numeric types
Note : If string s is empty with Atoi, the return value is 0. It is not possible to determine if s is 0 or null
1. Atoi (): int atoi (const char * str);
Description: Parses the C string str interpreting its content as a integral number, which is returned as an int valu E.
parameter: str : C string beginning with the representation of a integral number.
return value: 1. The successful conversion displays a value of type int. 2. the non-convertible string returns 0. 3. if the buffer overflows after the conversion, return Int_max orint_min
Demo:
[CPP]View Plaincopy
- #include <iostream>
- Using namespace std;
- int main ()
- {
- int i;
- char szinput [256];
- cout<<"Enter a number:" <<endl;
- Fgets (Szinput, stdin);
- i = atoi (szinput);
- cout<<"The value entered is:" <<szInput<<endl;
- cout<<"The number convert is:" <<i<<endl;
- return 0;
- }
Output:
Enter a number:48 The value entered is:48 The number convert is:48 |
2.aotl (): Long int atol (const char * str);
Description: C string str interpreting its content as an integral number, which is returned as a long int value (usage and at Oi function similar, return value is long int)
3.atof (): Double atof (const char * str);
Parameters: C string beginning with the representation of a floating-point number.
return Value: 1. Conversion successfully returns a value of type Doublel 2. Cannot convert, return 0.0. 3. Cross-border, return to huge_val
Demo:
[CPP]View Plaincopy
- /* Atof example:sine Calculator */
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- int main ()
- {
- double n,m;
- double pi=3.1415926535;
- char szinput [256];
- printf ( "Enter degrees:");
- Gets (Szinput);
- convert//char type to double type
- n = atof (szinput);
- m = sin (n*pi/180);
- printf ( "The sine of%f degrees is%f\n", N, m);
- return 0;
- }
C + + Converts a string type to int, float, and double type mainly in the following ways: