zoukankan      html  css  js  c++  java
  • c/c++再学习:常用字符串转数字操作

    c/c++再学习:常用字符串转数字操作

    能实现字符串转数字有三种方法,atof函数,sscanf函数和stringstream类。

    具体demo代码和运行结果

    #include "stdio.h"
    #include <iostream>
    #include <>
    int main()
    {
    	printf("字符串转数字:stof()函数 string转单精度浮点数
    ");
    	std::string stof_str("686.123456789123456");
    	float stof_val = std::stof(stof_str);
    	printf("stof_val=%.9f
    ", stof_val);
    
    	printf("字符串转数字:stod()函数 string转双精度浮点数
    ");
    	std::string stod_str("686.123456789123456");
    	double stod_val = std::stod(stod_str);
    	printf("stod_val=%.9f
    ", stod_val);
    
    	printf("字符串转数字:atof()函数
    ");
    	char* atof_str = "123.123456789123456";
    	double atof_val = atof(atof_str);
    	printf("atof_val=%.9f
    ", atof_val);
    
    	printf("字符串转数字:sscanf()函数
    ");
    
    	char* strInt = "123456789";
    	int   strInt_num = 0;
    	sscanf(strInt, "%d", &strInt_num);
    	printf("strInt_num=%d
    ", strInt_num);
    
    	char* strLong = "1234567890123456789";
    	long long  strLong_num = 0;
    	sscanf(strLong, "%lld", &strLong_num);
    	printf("strLong_num=%lld
    ", strLong_num);
    
    	char* strFloat = "1.23456789";
    	float strFloat_num = 0.0;
    	sscanf(strFloat, "%f", &strFloat_num);
    	printf("strFloat_num=%f
    ", strFloat_num);
    
    	char* strDouble = "1.23456789";
    	double strDouble_num = 0.0;
    	sscanf(strDouble, "%lf", &strDouble_num);
    	printf("strDouble_num=%.8lf
    ", strDouble_num);
    
    	printf("字符串转数字:stringstream类
    ");
    
    	stringstream ss;
    
    	ss.clear();
    	printf("stringstream precision=%d
    ", ss.precision());
    	string string_val1 = "1234567890";
    	int val1 = 0;
    	ss.str(string_val1);
    	ss >> val1;
    	printf("val1=%d
    ", val1);
    
    	ss.clear();
    	string string_val2 = "1.234567890123456789";
    	double val2 = 0;
    	ss.str(string_val2);
    	ss >> val2;
    	printf("val2=%.9f
    ", val2);
    
    }
    

    运行结果
    字符串转数字:stof()函数 string转单精度浮点数
    stof_val=686.123474121
    字符串转数字:stod()函数 string转双精度浮点数
    stod_val=686.123456789
    字符串转数字:atof()函数
    atof_val=123.123456789
    字符串转数字:sscanf()函数
    strInt_num=123456789
    strLong_num=1234567890123456789
    strFloat_num=1.234568
    strDouble_num=1.23456789
    字符串转数字:stringstream类
    stringstream precision=6
    val1=1234567890
    val2=1.234567890

  • 相关阅读:
    SDUT-3376_数据结构实验之查找四:二分查找
    SDUT-3375_数据结构实验之查找三:树的种类统计
    SDUT-3373_数据结构实验之查找一:二叉排序树
    深度优先遍历和广度优先遍历
    SDUT-2498_AOE网上的关键路径
    SDUT-2140_判断给定图是否存在合法拓扑序列
    SDUT-2144_最小生成树
    SDUT-3364_欧拉回路
    SDUT-3363_驴友计划
    Java练习 SDUT-2271_Eddy的难题
  • 原文地址:https://www.cnblogs.com/langzou/p/9844700.html
Copyright © 2011-2022 走看看