C++ stringstream realizes the conversion between characters and numbers

C++ stringstream realizes the conversion between characters and numbers

Ginkgo follow

0.408 2018.02.19 23:02:04 Word count 30 Reading 1,904

  1. String to number
#include<iostream>  
#include <sstream>   
#include <string>
using namespace std; 
int main()
{
    //字符转数字
    string str1 = "2018219";
    string str2 = "2018.219";//浮点数转换后的有效数为6位
    int num1 = 0;
    double num2 = 0.0;
    stringstream s;
    //转换为int类型
    s << str1;
    s >> num1;
    //转换为double类型
    s.clear();
    s << str2;
    s >> num2;
    cout << num1 << "\n" << num2 << endl;
    return 0;
}

The output is:
2018219
2018.22 // The effective number is 6 digits

  1. Number to string
#include "stdafx.h"
#include<iostream>  
#include <sstream>   
#include <string>
using namespace std; 
int main()
{
    string str1;
    string str2 ;
    int num1 = 2018219;
    double num2 = 2018.219;
    stringstream s;
    s << num1;
    s >> str1;
    s.clear();
    s << num2;
    s >> str2;
    cout << str1 << "\n" << str2 << endl;
    return 0;
}

The output is:
2018219
2018.22

Guess you like

Origin blog.csdn.net/digitalkee/article/details/108237510