c++ 數字/字符串轉換
1. 數字to字符串
- 方法一(利用<sstream>的stringstream,可以是浮點數)
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
double x;
string str;
stringstream ss;
cin >> x;
ss << x;
ss >> str;
cout << str;
return 0;
}
2.方法二(利用<sstream>中的to_string()方法,浮點數會附帶小數點后六位,不足補零,不推薦浮點數使用)
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
double x;
string str;
cin >> x;
str = to_string(x);
cout << str;
return 0;
}
2. 字符串to數字
-
方法一(利用<sstream>的stringstream,可以是浮點數)
#include <iostream> #include <sstream> using namespace std; int main() { double x; string str; stringstream ss; cin >> str; ss << str; ss >> x; cout << x; return 0; }
-
方法二(利用<string>中的stoi()函數,其中還有對於其他類型的函數,如stod(),stof()等,根據類型選取)
#include <iostream> #include <string> using namespace std; int main() { int x; string str; cin >> str; x = stoi(str); cout << x; return 0; }