c++ 如何将string 转化int的方法

不用 atoi() 不用std::stringistream ,求个函数原型

C++ 字符串string和整数int的互相转化操作

这篇文章主要介绍了C++ 字符串string和整数int的互相转化操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
一、string转int的方式
1、采用最原始的string, 然后按照十进制的特点进行算术运算得到int,但是这种方式太麻烦,这里不介绍了。

2、采用标准库中atoi函数。

string s = "12";

int a = atoi(s.c_str());

对于其他类型也都有相应的标准库函数,比如浮点型atof(),long型atol()等等。

3、采用sstream头文件中定义的字符串流对象来实现转换。

istringstream is("12"); //构造输入字符串流,流的内容初始化为“12”的字符串
int i;
is >> i; //从is流中读入一个int整数存入i中
二、int转string的方式
1、采用标准库中的to_string函数。

int i = 12;

cout << std::to_string(i) << endl;

不需要包含任何头文件,应该是在utility中,但无需包含,直接使用,还定义任何其他内置类型转为string的重载函数,很方便。

2、采用sstream中定义的字符串流对象来实现。

ostringstream os; //构造一个输出字符串流,流内容为空
int i = 12;
os << i; //向输出字符串流中输出int整数i的内容
cout << os.str() << endl; //利用字符串流的str函数获取流中的内容
字符串流对象的str函数对于istringstream和ostringstream都适用,都可以获取流中的内容。

补充知识:C++ 将整数、浮点数转为字符串

前言:

用 sprintf可以把整数、浮点数转为字符串。

1、整数

int main(int argc, const char * argv[]) {
int n = 12345;//待转整数
char strN[50];//转换后的字符串
sprintf(strN, "%d", n);
cout<<strN<<endl;//输出
return 0;
}
结果:

2、浮点数

int main(int argc, const char * argv[]) {
float n = 12345.67;//待转整数
char strN[50];//转换后的字符串
sprintf(strN, "%.2f", n);
cout<<strN<<endl;
return 0;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-02-27

方法一:使用C标准库里面的atoi;

方法二:使用C++标准库里面的stringstream。

例如:

//参考代码如下:
#include "iostream"
#include "stdlib.h"
#include "cstdlib"
#include "string"
#include "sstream"
using namespace std;
int main()
{
std::string s = "152";
std::stringstream ss;
//方法一: 
int num1 = std::atoi( s.c_str() );
cout<<num1<<endl;

//方法二:
int num2;
ss<<s;
ss>>num2;
cout<<num2<<endl; 
return 0;
}
/*
运行结果:
152
152
*/

本回答被网友采纳
第2个回答  2015-10-10
有两种方法
1. c++中string到int的转换

1) 在C标准库里面,使用atoi:

#include <cstdlib>
#include <string>

std::string text = "152";
int number = std::atoi( text.c_str() );
if (errno == ERANGE) //可能是std::errno
{
//number可能由于过大或过小而不能完全存储
}
else if (errno == ????)
//可能是EINVAL
{
//不能转换成一个数字
}

2) 在C++标准库里面,使用stringstream:(stringstream 可以用于各种数据类型之间的转换)

#include <sstream>
#include <string>

std::string text = "152";
int number;
std::stringstream ss;

ss << text;//可以是其他数据类型
ss >> number; //string -> int
if (! ss.good())
{
//错误发生
}

ss << number;// int->string
string str = ss.str();
if (! ss.good())
{
//错误发生
}

望采纳哦,亲
第3个回答  推荐于2017-11-25
int str2int(const char *s) {
    int sign = 1, value = 0;
    if (*s == '+') {
        ++s;
    } else if (*s == '-') {
        ++s;
        sign = -1;
    }
    while (*s) {
        if (*s >= '0' && *s <= '9') {
            value = value * 10 + *s - '0';
            ++s;
        } else {
            break;
        }
    }
    return sign * value;
}

追问

我也这么想的,是个面试题目。我工作也有1年经验了,换个工作,感觉不会出这么简单的题目,想给应届毕业生的

追答

请采纳,谢谢.. :-)

本回答被提问者采纳
第4个回答  2013-05-31
不用 atoi()不用std::stringistream,,C++11还有std::stoi ,这个函数还可以转换std::string到任意进制的int数……