1. 程式人生 > 實用技巧 >數字與字串相互轉化的方法

數字與字串相互轉化的方法

1.將數字轉化為字串

方法1:

#include<iostream>
using namespace std;
int main() {
    int n = 123;
    cout << to_string(n) << endl; 
    return 0;
}

方法2:

#include <iostream>
#include <sstream> using namespace std; int main() { int n = 123; string s; stringstream stream; stream
<< n; stream >> s; cout << s << endl; return 0; }

2.將字串轉化為數字

方法1:

#include <iostream>
#include <sstream>//標頭檔案 
using namespace std;
int main() {
    int n;
    string s;
    getline(cin, s);
    stringstream stream;
    stream << s;//將string型別存放在輸入流中 
stream >> n;//將從string型別的值賦給int型別的n cout << n; return 0; }

方法2:

將字串型別轉化為整型 (c++11)

#include <iostream>
#include <cstring> //函式的標頭檔案 
using namespace std;
int main() {
string s = "123";
int n = stoi(s);
cout << n;
return 0;
}