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

  • 相关阅读:
    zoj1654二分图
    zoj1314无源汇有上下界最大流
    zoj2788最小割
    zoj2587唯一最小割
    poj1815最小割
    Loader之一:基本原理
    Fragment之三:根据屏幕尺寸加载不同的Fragment
    Fragment之一:Fragment入门
    Github android客户端源代码分析之一:环境搭建
    如何在Eclipse中查看Android API源码以及support包源码
  • 原文地址:https://www.cnblogs.com/langzou/p/9844700.html
Copyright © 2011-2022 走看看