如何将 std::string 转换为 int? [英] How can I convert a std::string to int?

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

问题描述

有一个简单的问题.我在互联网上看了很多,我找到了一些解决方案,但没有一个有效.将字符串转换为 int 并不是指 ASCII 代码.

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.

为了快速了解,我们将一个等式作为字符串传递.我们要把它分解,正确格式化并求解线性方程.现在,说到这里,我无法将字符串转换为 int.

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.

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

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?

我想的一种方法是在字符串中运行 for/while 循环,检查一个数字,然后提取所有数字,然后查看是否有前导-",如果有,则乘以int by -1.

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?

推荐答案

在 C++11 中,有一些不错的从 std::string 转换为数字类型的新函数.

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

所以代替

atoi( str.c_str() )

你可以使用

std::stoi( str )

其中 str 是您作为 std::string 的号码.

where str is your number as std::string.

有适用于所有数字的版本:long stol(string), float stof(string), double stod(string),...见 http://en.cppreference.com/w/cpp/string/basic_string/stol

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

这篇关于如何将 std::string 转换为 int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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