c和c++如何把一個整數轉化爲string
轉載自:https://www.cnblogs.com/A-Little-Nut/p/8056421.html
原作者:A-Little-Nut
C++:
一、string轉int的方式
- 採用最原始的string, 然後按照十進制的特點進行算術運算得到int,但是這種方式太麻煩,這裏不介紹了。
- 採用標準庫中atoi函數。
string s = "12";
int a = atoi(s.c_str());
對於其他類型也都有相應的標準庫函數,比如浮點型atof(),long型atol()等等。
3. 採用sstream頭文件中定義的字符串流對象來實現轉換。
istringstream is("12"); //構造輸入字符串流,流的內容初始化爲“12”的字符串
int i;
is >> i; //從is流中讀入一個int整數存入i中
二、int轉string的方式
- 採用標準庫中的to_string函數。
int i = 12;
cout << std::to_string(i) << endl;
不需要包含任何頭文件,應該是在utility中,但無需包含,直接使用,還定義任何其他內置類型轉爲string的重載函數,很方便。
2.採用sstream中定義的字符串流對象來實現。
ostringstream os; //構造一個輸出字符串流,流內容爲空
int i = 12;
os << i; //向輸出字符串流中輸出int整數i的內容
cout << os.str() << endl; //利用字符串流的str函數獲取流中的內容
字符串流對象的str函數對於istringstream和ostringstream都適用,都可以獲取流中的內容。
C:
#include "stdio.h"
#include <stdlib.h>
#include <string.h>
void main()
{
int n=123456789;
char str[20];
itoa(n, str, 10);
printf("%s\n",str);
}
作者:A-Little-Nut
歡迎任何形式的轉載,但請務必註明出處。
限於本人水平,如果文章和代碼有表述不當之處,還請不吝賜教。