c++如何把string里的数字转为int型。比如123/896要转换为两个数字一百二十三和八百九

c++如何把string里的数字转为int型。比如123/896要转换为两个数字一百二十三和八百九十六

利用string类的查找方法int find(char c, int pos = 0) const;
找到/所在的位置,
然后使用string类的assign()方法,将123和896分开成两个string对象,
最后使用atoi()函数就可以得到整型数了。
代码示例:
string a("123/896");

string b,c;

int pos;

pos=a.find('/');

b.assign(a,0,pos);

c.assign(a,pos+1,a.length());

cout << atoi(b.c_str()) << endl;

cout << atoi(c.c_str()) << endl;追问

如果对这个处理的话是看成一百二十三处理吗

追答

atoi(b.c_str())的值就是一百二十三,是个整数

追问

头文件主要string就行了?

追答

#include
#include

using namespace std;

追问

编译不能过

为什么不能直接atoi(b)

追答

你的编译器报什么error?
我的编译器上这样就已经能正常执行了:
#include

using namespace std;

int main(int argc, char* argv[])

{

string a("123/896");

string b,c;

int pos;

pos=a.find('/');

b.assign(a,0,pos);

c.assign(a,pos+1,a.length());

cout << atoi(b.c_str()) << endl;

cout << atoi(c.c_str()) << endl;

return 0;

}

追问

用你的可以了

atoi(b)不行

c语言结构体删除。就是指定一个位置然后删除,就像是队列,叫一个人出列,后面的人往前。最后要输出没有出列的

这个有什么函数吗

追答

atoi()函数的参数类型是char *型,而b是string型,两者不同,所以atoi(b)编译是过不了的,b.c_str()是将string型转成char *型的方法,所以要用atoi(b.c_str())

追问

那我问的结构体删除有什么函数

追答

C语言里没有现成的函数可用,但C++的vector类就是这样的队列,用它的erase()方法可以轻松地删除一个元素,后面的元素会自动往前。

追问

那如果一开始是用结构体来储存名字和号码,那就只能一个个赋值到vector

问一下,是不是结构体不能b【1】=b【2】

追答

结构体可以b【1】=b【2】的

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-03-30
大致2种方法吧
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())
{
//错误发生
}
第2个回答  2016-03-30
int atoi( const char* string );
相似回答