c++ 數字與字符串的相互轉換


c++ 數字/字符串轉換

1. 數字to字符串

  1. 方法一(利用<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數字

  1. 方法一(利用<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;
    }
    
  2. 方法二(利用<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;
    }
    


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM