SoFunction
Updated on 2025-04-07

Example of the implementation of converting numbers and strings between C/C++

1. To string

1. Method 1 (Use the <sstream> stringstream,Can be a floating point number

#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. Method 2 (Use theto_string()method,Floating points will come with six decimal places, which is not enough to make up for zeros, and it is not recommended to use floating points.

#include <iostream>
#include <sstream>
using namespace std;
int main()
{
    double x;
    string str;
    cin >> x;
    str = to_string(x);
    cout << str;
    return 0;
}

1. To string to number

1. Method 1 (Use the <sstream> stringstream,Can be a floating point number)

#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. Method 2 (Use thestoi()function,There are also functions of other types, such as stod(), stof(), etc., selected according to the type

#include <iostream>
#include <string>
using namespace std;
int main()
{
    int x;
    string str;
    cin >> str;
    x = stoi(str);
    cout << x;
    return 0;
}

This is the article about the implementation example of the conversion of C/C++ numbers and strings. For more related contents of converting C/C++ numbers and strings, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!