本文介绍了如何将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)等,因此绝对是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?

我想到的一种方式是在字符串中运行for / while循环,检查一个数字,提取所有数字之后,然后查看是否有前导-,如果有,则将int乘以-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有一些不错的新转换函数:字符串转换为数字类型。

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.

有各种版本的数字:
长号stol(string) float stof(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

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

08-20 04:45