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

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

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

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

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


当前回答

我认为从int转换为std::string或反之亦然需要一些特殊的函数,如std::stoi() 但是如果你需要将double类型转换为字符串,请使用to_string()(不是c#。c#是.ToString()而不是to_string()

其他回答

在c++ 11中,我们可以使用"stoi"函数将字符串转换为int型

#include <iostream>
#include <string>
using namespace std;
 
int main()
{
    string s1 = "16";
    string s2 = "9.49";
    string s3 = "1226";
 
    int num1 = stoi(s1);
    int num2 = stoi(s2);
    int num3 = stoi(s3);
 
    cout << "stoi(\"" << s1 << "\") is " << num1 << '\n';
    cout << "stoi(\"" << s2 << "\") is " << num2 << '\n';
    cout << "stoi(\"" << s3 << "\") is " << num3 << '\n';
 
    return 0;
}

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";
 }

可能有点过分了,但是 boost::lexical_cast<int>(theString)应该是作业 很好。

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

string a = "25";

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

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

诚然,我的解决方案不适用于负整数,但它将从包含整数的输入文本中提取所有正整数。它使用numeric_only locale:

int main() {
        int num;
        std::cin.imbue(std::locale(std::locale(), new numeric_only()));
        while ( std::cin >> num)
             std::cout << num << std::endl;
        return 0;
}

输入文本:

 the format (-5) or (25) etc... some text.. and then.. 7987...78hjh.hhjg9878

输出整数:

 5
25
7987
78
9878

类numeric_only定义为:

struct numeric_only: std::ctype<char> 
{
    numeric_only(): std::ctype<char>(get_table()) {}

    static std::ctype_base::mask const* get_table()
    {
        static std::vector<std::ctype_base::mask> 
            rc(std::ctype<char>::table_size,std::ctype_base::space);

        std::fill(&rc['0'], &rc[':'], std::ctype_base::digit);
        return &rc[0];
    }
};

完整在线演示:http://ideone.com/dRWSj