C/C++ 字串轉數字的方法
C/C++ 字串轉數字的方法
資料來源: https://shengyu7697.github.io/cpp-string-to-integer/
https://www.cplusplus.com/reference/cstdlib/strtol/
https://www.tutorialspoint.com/compile_c_online.php
https://www.tutorialspoint.com/compile_cpp_online.php
01.純C寫法:
#include <stdio.h> #include <stdlib.h> int main() { char buffer[128] = "123"; int integer = atoi(buffer); printf("str to int: %d\n", integer); return 0; }
#include <stdio.h> #include <stdlib.h> int main() { char buffer[128] = "FF"; char * pEnd; int integer = strtol(buffer,&pEnd,16); printf("str to int: %d\n", integer); printf("str to int: %o\n", integer); printf("str to int: %x\n", integer); return 0; }
/* strtol example */ #include <stdio.h> /* printf */ #include <stdlib.h> /* strtol */ int main () { char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff"; char * pEnd; long int li1, li2, li3, li4; li1 = strtol (szNumbers,&pEnd,10); li2 = strtol (pEnd,&pEnd,16); li3 = strtol (pEnd,&pEnd,2); li4 = strtol (pEnd,NULL,0); printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4); return 0; } /* The decimal equivalents are: 2001, 6340800, -3624224 and 7340031 */
02.C++ 字串轉數字
#include <iostream> #include <cstdlib> using namespace std; int main() { cout << "Hello World" << endl; char buffer[128] = "456"; int integer = std::atoi(buffer); printf("str to int: %d\n", integer); return 0; }
One thought on “C/C++ 字串轉數字的方法”
C/C++ 數字轉字串的方法
https://bit.ly/3wMufOF