C/C++中數字與字符串之間的轉化

數字與字符串之間的轉化

在C中:

方法:

  • C標準庫中的sprintf,sscanf
  1. 字符串轉數字 sscanf  
#include<stdio.h>

//字符串轉數字
void Testsscanf()
{
	//字符串轉化爲整數
	char str1[] = "1234567";
	int a;
	sscanf(str1,"%d",&a);
	printf("%d\n",a);

	//字符串轉化爲浮點數
	char str2[] = "123.456";
	double d;
	sscanf(str2,"%lf",&d);
	printf("%lf\n",d);

        //十六進制轉化爲10進制
        char str3[10];
	int c=175;
	sprintf(str3,"%x",a);
	printf("%s\n",str1);
}

     2. 數字轉字符串 sprintf

//數字轉字符串
void Testsprintf()
{
	char str1[10];
	int a=1234321;
	sprintf(str1,"%d",a);
	printf("%s\n",str1);

	char str2[10];
	double b=123.321;
	sprintf(str2,"%.3lf",a);
	printf("%s\n",str1);

	char str3[10];
	int c=175;
	sprintf(str3,"%x",a);//10進制轉換成16進制,如果輸出大寫的字母是sprintf(str,"%X",a)
	printf("%s\n",str1);
}
  • C標準庫中的atoi、atof、atol、atoll(C++11標準)函數將字符串轉化爲int、double、long、long long 型
  1. atoi函數

        功能:把字符串轉化爲整形數

        原型: int atoi(const char *nptr);

   注:需要用到的頭文件: #include <stdlib.h>

     2.  itoa函數

     功能:將整形數轉化爲字符串

     原型:char *itoa(int value, char *string, int radix);

              value: 待轉化的整數。

              radix: 是基數的意思,即先將value轉化爲radix進制的數,範圍介於2-36,比如10表示10進制,16表示16進制。

             * string: 保存轉換後得到的字符串。

             返回值:char * : 指向生成的字符串, 同*string。

      注:需要用到的頭文件: #include <stdlib.h>

在C++中:

方法:用C++中stringstream;

注:需要引入頭文件 #include<sstream>

  • 數字轉字符串
#include<sstream>
#include<string>
string num2str(double i)
{
    stringstream ss;
    ss << i;
    return ss.str();
}
  • 字符串轉數字
#include<sstream>
#include<string>
int str2num(string s)
{
    int num;
    stringstream ss(s);
    ss >> num;
    return num;
}

更多使用詳見:

https://www.cnblogs.com/luxiaoxun/archive/2012/08/03/2621803.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章