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

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

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

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

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


当前回答

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

其他回答

要将字符串表示形式转换为整数值,可以使用std::stringstream。

如果转换的值超出整数数据类型的范围,则返回INT_MIN或INT_MAX。

此外,如果字符串值不能表示为有效的int数据类型,则返回0。

#include 
#include 
#include 

int main() {

    std::string x = "50";
    int y;
    std::istringstream(x) >> y;
    std::cout << y << '\n';
    return 0;
}

输出: 50

根据上面的输出,我们可以看到它从字符串数转换为整数数。

来源和更多的字符串int c++

一行版本:long n = strtol(s.c c_str(), NULL, base);.

(s为字符串,base为int,如2,8,10,16)

你可以参考这个链接了解更多关于strtol的细节。


核心思想是使用sttol函数,该函数包含在cstdlib中。

由于strtol只处理char数组,我们需要将字符串转换为char数组。你可以参考这个链接。

一个例子:

#include <iostream>
#include <string>   // string type
#include <bitset>   // bitset type used in the output

int main(){
    s = "1111000001011010";
    long t = strtol(s.c_str(), NULL, 2); // 2 is the base which parse the string

    cout << s << endl;
    cout << t << endl;
    cout << hex << t << endl;
    cout << bitset<16> (t) << endl;

    return 0;
}

它将输出:

1111000001011010
61530
f05a
1111000001011010

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

我知道这个问题很老了,但我认为有更好的解决方法

#include <string>
#include <sstream>

bool string_to_int(std::string value, int * result) {
  std::stringstream stream1, stream2;
  std::string stringednumber;
  int tempnumber;
  stream1 << value;
  stream1 >> tempnumber;
  stream2 << tempnumber;
  stream2 >> stringednumber;
  if (!value.compare(stringednumber)) {
    *result = tempnumber;
    return true;
  }
  else return false;
}

如果我写的代码是正确的,这将返回一个布尔值,告诉你如果字符串是一个有效的数字,如果为假,它不是一个数字,如果为真,它是一个数字,这个数字现在是结果,你会这样调用它:

std::string input;
std::cin >> input;
bool worked = string_to_int(input, &result);

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

string a = "25";

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

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