to_string | int to string將其他型轉換成字符串型 |
---|---|
atoi | ascii to integer是把字符串轉換成整型數的一個函數 |
to_string
#include <iostream> // std::cout
#include <string> // std::string, std::to_stringint main ()
{std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";std::cout << perfect << '\n';return 0;
}
把整型數據28(函數內部可進行運算)和后面的字符串” is a perfect number”進行合并
pi is 3.141593
28 is a perfect number
atoi
#include <stdio.h> /* printf, fgets */
#include <stdlib.h> /* atoi */int main ()
{int i;char buffer[256];printf ("Enter a number: ");fgets (buffer, 256, stdin);i = atoi (buffer);printf ("The value entered is %d. Its double is %d.\n",i,i*2);return 0;
}
Enter a number: 73
The value entered is 73. Its double is 146.
額外拓展了解即可
1.int/float to string/array:
● ultoa():將無符號長整型值轉換為字符串。
● gcvt():將浮點型數轉換為字符串,取四舍五入。
● ecvt():將雙精度浮點型值轉換為字符串,轉換結果中不包含十進制小數點。
● fcvt():指定位數為轉換精度,其余同ecvt()。
除此外,還可以使用sprintf系列函數把數字轉換成字符串,其比itoa()系列函數運行速度慢
2. string/array to int/float
C/C++語言提供了幾個標準庫函數,可以將字符串轉換為任意類型(整型、長整型、浮點型等)。
● atof():將字符串轉換為雙精度浮點型值。
● atol():將字符串轉換為長整型值。
● strtod():將字符串轉換為雙精度浮點型值,并報告不能被轉換的所有剩余數字。
● strtol():將字符串轉換為長整值,并報告不能被轉換的所有剩余數字。
● strtoul():將字符串轉換為無符號長整型值,并報告不能被轉換的所有剩余數字。