[C + +] string and int, float, double convert each other

Source: Internet
Author: User
Tags sprintf

Reference: http://blog.csdn.net/candadition/article/details/7342380

Converting a string type to an int, float, double type is primarily done 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.


#include <iostream>
#include <sstream> // This string needs to be introduced using stringstream
using namespace std;
// Template function: convert string type variables to commonly used numeric types (this method has universal applicability)
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;

Input Results 801

#method two: 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 anintvalu 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, returnInt_maxorint_min


#include <iostream> using namespace std; int main ()  
{ int i; char szInput [256];  
    cout<<"Enter a number: "<<endl;  
    fgets ( szInput, 256, stdin );  
    i = atoi (szInput);  
    cout<<"The value entered is :"<<szInput<<endl;  
    cout<<" The number convert is:"<<i<<endl; return 0;  


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 along intvalue (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 tohuge_val


/ * 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);
   // char type is converted 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 + + int type conversion String type

Reference: http://blog.csdn.net/candadition/article/details/7342092

In C + +, unlike C # or Java, you can directly use string addition to convert an int type to a string type. This type conversion in C + + requires some extra functions.

One, C + + int to string

#method one: Use the ITOA function: char * itoa (int value, char * str, int base);

description : Convert integer to String (non-standard function)


Value:value to being converted to a string. Str:array in memory where to store the resulting null-terminated string.  Base:numerical base used to represent the value as a string, between2and, wheremeans decimal base,hexadecimal,8octal, and2binary.


#include <iostream>
using namespace std;
int main (int argc, char * argv [])
     int n = 30;
     char c [10];
     // Binary conversion
     itoa (n, c, 2);
     cout << "2->" << c << endl;
     // decimal conversion
     itoa (n, c, 10);
     cout << "10->" << c << endl;
     // Hex conversion
     itoa (n, c, 16);
     cout << "16->" << c << endl;

     system ("pause");
     return 0;


2-> 11110  
10-> 30  
16-> 1e  

#method two: Use Sprintf:int sprintf (char * str, const char * format, ...);

Parameter description:

% The percent symbol is printed without conversion.

b Integer converted to binary.

c Integer is converted to the corresponding ASCII character.

d Integer converted to decimal.

F times precision converted to floating point.

o Integers are converted to octal.

s Integer into string.

x integers are converted to lowercase hexadecimal.

X integers are converted to uppercase hexadecimal. 


#include <iostream>
#include <string>
using namespace std;
int main ()
     int n = 30;
     char c [20]; // char * c;
     //% d decimal
     sprintf (c, "% d", n);
     cout << c << endl;
     //% o octal
     sprintf (c, "% o", n);
     cout << c << endl;
     //% X uppercase hexadecimal
     sprintf (c, "% X", n);
     cout << c << endl;
     //% cACSII characters
     sprintf (c, "% c", n);
     cout << c << endl;
     //% f floating point conversion
     float f = 24.678;
     sprintf (c, "% f", f);
     cout << c << endl;
     //%.2f "keep two decimal places
     sprintf (c, "% .2f", f);
     cout << c << endl;
     // Convert two numbers
     sprintf (c, "% d-%. 2f", n, f);
     cout << c << endl;

     system ("pause");
     return 0;


Note: Here is a special symbol  
30-24.68 #method three: Using StringStream

Input/output string Stream class:

StringStreamprovides an interface to manipulate strings as if they were input/output streams.

#include <iostream>
#include <string>
#include <sstream> // Introduce the stringstream header file
using namespace std;
int main ()
     stringstream strStream;
     int a = 100;
     float f = 23.5566;
     // int and float types can be stuffed into stringstream
     strStream << a << "----" << f;
     string s = strStream.str ();
     cout << s << endl;

     system ("pause");
     return 0;



#fourth, other

1.SPRINTF can cause buffer overflow, consider using snprintf or nonstandard asprintf

2. If it is an MFC program, you can use Cstring::format

3. If you use boost, you can use it directly: string s = Boost::lexical_cast <string> (a);

4.atoi is also non-portable.

[C + +] string and int, float, double convert each other

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.