我想将一个字符串转换为int,我不是指ASCII码。

为了快速回顾,我们将一个方程作为字符串传递。我们要把它分解,正确地格式化并解出线性方程。说到这里,我不能把一个字符串转换成int型。

我知道字符串的格式是(-5)或(25)等,所以它肯定是int型。但是我们如何从字符串中提取它呢?

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

对于这样一个小问题来说,这似乎有点过于复杂了。什么好主意吗?


当前回答

还有另一种简单的方法:假设你有一个像c='4'这样的字符,那么你可以执行以下步骤之一:

第一个:int q

Q =(int) c;(q现在在ASCII表中是52)。 q = q-48;记住,数字加48是他们的ASCII码。

第二种方式:

q = c - ' 0 ';同样,字符“0”表示48

其他回答

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

所以与其

atoi( str.c_str() )

你可以使用

std::stoi( str )

其中STR是你的数字std::string。

各种类型的数字都有对应的版本: 长stol(字符串),浮动stof(字符串),双stof(字符串),… 参见http://en.cppreference.com/w/cpp/string/basic_string/stol

使用atoi函数将字符串转换为整数:

string a = "25";

int b = atoi(a.c_str());

http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/

std::istringstream ss(thestring);
ss >> thevalue;

为了完全正确,您需要检查错误标志。

1. std:: stoi

std::string str = "10";  
int number = std::stoi(str); 

2. 字符串流

std::string str = "10";  
int number;  
std::istringstream(str) >> number

3.boost:: lexical_cast

#include <boost/lexical_cast.hpp>
std::string str = "10";  
int number;
    
try 
{
    number = boost::lexical_cast<int>(str);
    std::cout << number << std::endl;
}
catch (boost::bad_lexical_cast const &e) // bad input
{
    std::cout << "error" << std::endl;
}

4. std:: atoi

std::string str = "10";
int number = std::atoi(str.c_str()); 

5. sscanf ()

 std::string str = "10";
 int number;
 if (sscanf(str .c_str(), "%d", &number) == 1) 
 {
     std::cout << number << '\n';
 } 
 else 
 {
     std::cout << "Bad Input";
 }
ll toll(string a){
    ll ret=0;
    bool minus=false;
    for(auto i:a){
        if(i=='-'){ minus=true; continue; }
        ret*=10;
        ret+=(i-'0');
    } if(minus) ret*=-1;
    return ret;
    # ll is defined as, #define ll long long int
    # usage: ll a = toll(string("-1234"));
}