在 C/C++ 中將字串轉換為數字
本教程介紹一個程式,用來理解如何在 C/C++ 中將字串轉換位數字。
C/C++ 提供兩種方法將字串轉換為數字。
範例
使用 sscanf()
#include<stdio.h>
int main(){
const char *str = "12345";
int x;
sscanf(str, "%d", &x);
printf("\nThe value of x : %d", x);
return 0;
}輸出
The value of x : 12345
使用 stoi()
#include <iostream>
#include <string>
using namespace std;
int main(){
string str1 = "45";
string str2 = "3.14159";
string str3 = "31337 geek";
int myint1 = stoi(str1);
int myint2 = stoi(str2);
int myint3 = stoi(str3);
cout << "stoi(\"" << str1 << "\") is " << myint1 << '\n';
cout << "stoi(\"" << str2 << "\") is "<< myint2 << '\n';
cout << "stoi(\"" << str3 << "\") is "<< myint3 << '\n';
return 0;
}輸出
stoi("45") is 45
stoi("3.14159") is 3
stoi("31337 geek") is 31337
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP