[C++] string与int, float, double相互转换
参考:http://blog.csdn.net/candadition/article/details/7342380
将string类型转换为int, float, double类型 主要通过以下几种方式:
# 方法一: 使用stringstream
stringstream在int或float类型转换为string类型的方法中已经介绍过, 这里也能用作将string类型转换为常用的数值类型。
Demo:
#include <iostream>
#include <sstream> //使用stringstream需要引入这个头文件
using namespace std; //模板函数:将string类型变量转换为常用的数值类型(此方法具有普遍适用性)
template <class Type>
Type stringToNum(const string& str)
{
istringstream iss(str);
Type num;
iss >> num;
return num;
} int main(int argc, char* argv[])
{
string str("");
cout << stringToNum<int>(str) << endl; system("pause");
return ;
输入结果 801
#方法二:使用atoi()、 atil() 、atof()函数 -----------------实际上是char类型向数值类型的转换
注意:使用 atoi 的话,如果 string s 为空,返回值为0.则无法判断s是0还是空
1. atoi(): int atoi ( const char * str );
说明:Parses the C string str interpreting its content as an integral number, which is returned as an int value.
参数:str : C string beginning with the representation of an integral number.
返回值:1. 成功转换显示一个Int类型的值. 2. 不可转换的字符串返回0. 3.如果转换后缓冲区溢出,返回 INT_MAX orINT_MIN
Demo:
#include <iostream>
using namespace std;
int main ()
{
int i;
char szInput [];
cout<<"Enter a number: "<<endl;
fgets ( szInput, , stdin );
i = atoi (szInput);
cout<<"The value entered is :"<<szInput<<endl;
cout<<" The number convert is:"<<i<<endl;
return ;
}
输出
Enter a number: 48
The value entered is : 48
The number convert is: 48
2.aotl(): long int atol ( const char * str );
说明:C string str interpreting its content as an integral number, which is returned as a long int value(用法和atoi函数类似,返回值为long int)
3.atof(): double atof ( const char * str );
参数:C string beginning with the representation of a floating-point number.
返回值:1. 转换成功返回doublel类型的值 2.不能转换,返回0.0。 3.越界,返回HUGE_VAL
Demo:
/* atof example: sine calculator */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main ()
{
double n,m;
double pi=3.1415926535;
char szInput [];
printf ( "Enter degrees: " );
gets ( szInput );
//char类型转换为double类型
n = atof ( szInput );
m = sin (n*pi/);
printf ( "The sine of %f degrees is %f\n" , n, m ); return ;
}
C++ int类型转换string类型
参考:http://blog.csdn.net/candadition/article/details/7342092
C++中不像C#或Java中能直接使用字符串加法将 int类型转换为string类型。C++中进行这样的类型转换需要一些额外的函数。
一、C++的int转string
#方法一: 使用itoa函数: char * itoa ( int value, char * str, int base );
说明:Convert integer to string (non-standard function)
参数:
·value : Value to be converted to a string.·str : Array in memory where to store the resulting null-terminated string.·base : Numerical base used to represent the value as a string, between2 and36, where10 means decimal base, 16 hexadecimal,8 octal, and2 binary.
Demo:
#include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
int n = ;
char c[];
//二进制转换
itoa(n, c, );
cout << "2-> " << c << endl;
//十进制转换
itoa(n, c, );
cout << "10-> " << c << endl;
//十六进制转换
itoa(n, c, );
cout << "16-> " << c << endl; system("pause");
return ;
}
输出:
2-> 11110
10-> 30
16-> 1e
#方法二: 使用sprintf: int sprintf ( char * str, const char * format, ... );
参数说明:
% 印出百分比符号,不转换。 b 整数转成二进位。 c 整数转成对应的 ASCII 字元。 d 整数转成十进位。 f 倍精确度数字转成浮点数。 o 整数转成八进位。 s 整数转成字串。 x 整数转成小写十六进位。 X 整数转成大写十六进位。
Demo:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n = ;
char c[]; //char *c;
//%d十进制
sprintf(c, "%d", n);
cout << c << endl;
//%o八进制
sprintf(c, "%o", n);
cout << c << endl;
//%X大写十六进制
sprintf(c, "%X", n);
cout << c << endl;
//%cACSII字元
sprintf(c, "%c", n);
cout << c << endl; //%f浮点数转换
float f = 24.678;
sprintf(c, "%f", f);
cout << c << endl;
//%.2f"保留小数点后面两位
sprintf(c, "%.2f", f);
cout << c << endl;
//转换两个数
sprintf(c, "%d-%.2f", n, f);
cout << c << endl; system("pause");
return ;
}
输出:
30
36
1E
//注:这里是个特殊符号
24.677999
24.68
30-24.68 #方法三:使用stringstream
Input/output string stream class:
stringstream provides an interface to manipulate strings as if they were input/output streams.
#include <iostream>
#include <string>
#include <sstream> //引入stringstream头文件
using namespace std;
int main()
{
stringstream strStream;
int a = ;
float f = 23.5566;
//int、float类型都可以塞到stringstream中
strStream << a << "----"<< f ;
string s = strStream.str();
cout << s << endl; system("pause");
return ;
}
输出:
100----23.5566
#四、其他
1.sprintf可能引起缓冲区溢出,可以考虑使用 snprintf 或者非标准的 asprintf
2.如果是mfc程序,可以使用 CString::Format
3.如果使用boost,则可以直接使用: string s = boost::lexical_cast <string>(a);
4.atoi 也是不可移植的。
[C++] string与int, float, double相互转换的更多相关文章
- C++中将string类型转换为int, float, double类型 主要通过以下几种方式:
C++中将string类型转换为int, float, double类型 主要通过以下几种方式: # 方法一: 使用stringstream stringstream在int或float类型转换为 ...
- 关于c中 int, float, double转换中存在的精度损失问题
先看一段代码实验: #include<limits> #include<iostream> using namespace std; int main() { unsigned ...
- QT中QString 与 int float double 等类型的相互转换
Qt中 int ,float ,double转换为QString 有两种方法 1.使用 QString::number(); 如: long a = 63; QString s = QString:: ...
- C 语言实例 - 计算 int, float, double 和 char 字节大小
C 语言实例 - 计算 int, float, double 和 char 字节大小 C 语言实例 C 语言实例 使用 sizeof 操作符计算int, float, double 和 char四种变 ...
- Android中 int,float,Double,String 互相转换
1 如何将字串 String 转换成整数 int? A. 有两个方法: 1). int i = Integer.parseInt([String]); 或 i = Integer.parseInt( ...
- C++11中int,float,double与string的转化
在C++11中可以使用std::to_string()函数将数值转换为string格式,十分方便. 以下部分来选自cplusplus.com. std::to_string string to_str ...
- int, float, double 等转化为 string
一般有以下两种方法: QVecotr<int> vec; QString(QByteArray().setNum(vec.at(3))) float f; QString("%1 ...
- sql server数据库如何存储数组,int[]float[]double[]数组存储到数据库方法
原文地址:https://www.zhaimaojun.top/Note/5475296 将数组存储到数据库的方法 (本人平时同csharp编写代码,所以本文中代码都是csharp代码,有些地方jav ...
- int float double 最小值与最大值
#include <iostream> #include <limits> using namespace std; int main() { cout << &q ...
随机推荐
- postman返回参数的截取
同事在使用postman接口测试的时候,遇到这么一个问题,在一个参数里面,返回了一个类似数组的参数,如下: 然后现在需要把数组里面的两个参数分别保存到环境变量里面: 个人的想法是通过截取的方式进行数组 ...
- javascript console自动点击页面元素
原文地址https://jingyan.baidu.com/article/0a52e3f41c0b0abf63ed726d.html 这里拿百度音乐VIP兑换页面来做演示. 首先打开百度音乐VIP兑 ...
- 做报表需要知道的基本的SQL语句
为客户做报表需要操作数据库,基本的SQL是必须要掌握的,下面介绍做报表最常用的SQL语句. 方法/步骤 1 查询数据:编号表示查询顺序. (8) select (9) distinct (11 ...
- 24最小生成树之Prim算法
最小生成树的Prim算法 思想:采用子树延伸法 将顶点分成两类: 生长点——已经在生成树上的顶点 非生长点——未长到生成树上的顶点 使用待选边表: 每个非生长点在待选边表中有一条待选边,一端连着非生长 ...
- 排序-----插入排序(python版)
直接插入排序的算法思路: (1) 设置监视哨r[0],将待插入纪录的值赋值给r[0]: (2) 设置开始查找的位置j: (3) 在数组中进行搜索,搜索中将第j个纪录后移,直至r[0].key≥r[j] ...
- Ignite初探
Guava是一个很方便的本地缓存工具,但是在多节点处理的过程中,本地缓存无法满足数据一致性的问题.分布式缓存Ignite很好的解决了数据一致性,可靠性,事务性等方面的问题. Ignite支持分区方式和 ...
- linux基础命令---touch
touch 将文件的访问时间和修改时间修改为当前时间.如果指定的文件不存在,那么将会创造空文件,除非指定-c或-h选项.文件参数字符串‘-‘被专门处理,并导致touch更改与标准输出相关联的文件的时间 ...
- php抛出异常
php抛出异常:throw new Exception("xxxxxx!"); 实例代码: try{ if ($mysqli->connect_errno) { sleep( ...
- PHP二维数组排序(感谢滔哥lvtao.net)
滔哥原创 /* _ooOoo_ o8888888o 88" . "88 (| -_- |) O\ = /O ____/`---'\____ .' \\| |// `. / \\|| ...
- mamcached+magent构建memcached集群
cat /etc/redhat-release CentOS release 6.7 (Final) 防火墙.selinux 关闭 192.168.12.30 安装libevent和memcached ...