将字符串转换为整数 [英] Converting string to integer

查看:100
本文介绍了将字符串转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串:


string A =" 2";


我需要得到它的整数值:


// ??

int val = A; // ??

解决方案

>我有一个字符串:


字符串A =" 2" ;;

我需要得到它的整数值:

// ??
int val = A; // ??



假设你包含stdlib.h并且string-class为const char提供了

cast-operator *:


int val = atoi(string);




" Gil" <峰; br ************** @ hotmail.com>在消息中写道

新闻:ad ************************* @ posting.google.co m ... < blockquote class =post_quotes>我有一个字符串:

字符串A =" 2" ;;

我需要得到它的整数值:



查看 http://www.groups。 google.com


无论如何,

int main()

{

string str =" 123";

istringstream iss(str);

int x;

iss>> x;

if(iss)

{

//转换成功

}

else

{

//无法将str转换为int

}

}


祝福,

Sharad




" Patrik Stellmann" < ST ******* @ tu-harburg.de>在消息中写道

news:bv ************ @ uni-berlin.de ...

我有一个字符串:

字符串A =" 2" ;;

我需要得到它的整数值:

/ / ??
int val = A; // ??假设你包含stdlib.h并且string-class为const char提供了
cast-operator *:




抱歉,这两个假设都是错误的。

包含的标准标题是< cstdlib>如今。此外,字符串类不提供

隐式const char *转换,而是提供c_str()成员函数。

int val = atoi(string);




int val = atoi(A.c_str());


应该可以解决问题。


问候

Chris


I have a string :

string A = "2";

I need to get it''s integer value :

// ??
int val = A ; // ??

解决方案

> I have a string :


string A = "2";

I need to get it''s integer value :

// ??
int val = A ; // ??


assuming you include stdlib.h and the string-class provides the
cast-operator to const char*:

int val = atoi(string);



"Gil" <br**************@hotmail.com> wrote in message
news:ad*************************@posting.google.co m...

I have a string :

string A = "2";

I need to get it''s integer value :



Check http://www.groups.google.com

Anyways,
int main()
{
string str = "123";
istringstream iss(str);
int x;
iss >> x;
if(iss)
{
// conversion successful
}
else
{
// could not convert str to an int
}
}

Best wishes,
Sharad



"Patrik Stellmann" <st*******@tu-harburg.de> wrote in message
news:bv************@uni-berlin.de...

I have a string :

string A = "2";

I need to get it''s integer value :

// ??
int val = A ; // ?? assuming you include stdlib.h and the string-class provides the
cast-operator to const char*:



Sorry, but both of these assumptions are incorrect. The standard header to
include is <cstdlib> nowadays. Furthermore the string class does not provide
an implicit const char* conversion but rather the c_str() member function.

int val = atoi(string);



int val = atoi( A.c_str() );

should do the trick.

Regards
Chris


这篇关于将字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆