将字符串转换为int C ++ [英] Convert string to int C++

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

问题描述

只是有一个快速问题。我已经看过互联网了很多,我找到了一些解决方案,但没有一个工作了。看看将字符串转换为int,我不是指ASCII码。



对于快速下移,我们在方程式中作为字符串传递。我们要把它分解,正确格式化并求解线性方程。现在,在说,我不能将一个字符串转换为一个int。



我知道字符串将是格式(-5)或(25)等等,所以它绝对是一个int。但是我们如何从字符串中提取呢?



一种方式是我正在运行一个for循环通过字符串,检查一个数字,提取所有的数字然后看看是否有一个前导' - ',如果有,将int乘以-1。



看起来有点复杂一个小问题。任何想法?

解决方案

在C ++ 11中有一些不错的新转换函数 std ::


$ b

$

code> atoi(str.c_str())

您可以使用

  std :: stoi(str)

其中 str 是您的号码 std :: string



有所有版本的数字:
long stol(string) float stof double stod(string),...
请参阅 http://en.cppreference.com/w/cpp/string/basic_string/stol


Just have a quick question. I've looked around the internet quite a bit and I've found a few solutions but none of them have worked yet. Looking at converting a string to an int and I don't mean ASCII codes.

For a quick run-down, we are passed in an equation as a string. We are to break it down, format it correctly and solve the linear equations. Now, in saying that, I'm not able to convert a string to an int.

I know that the string will be in either the format (-5) or (25) etc. so it's definitely an int. But how do we extract that from a string?

One way I was thinking is running a for/while loop through the string, check for a digit, extract all the digits after that and then look to see if there was a leading '-', if there is, multiply the int by -1.

It seems a bit over complicated for such a small problem though. Any ideas?

解决方案

In C++11 there are some nice new convert functions from std::string to a number type.

So instead of

atoi( str.c_str() )

you can use

std::stoi( str )

where str is your number as std::string.

There are version for all flavours of numbers: long stol(string), float stof(string), double stod(string),... see http://en.cppreference.com/w/cpp/string/basic_string/stol

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

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