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

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

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

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

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


当前回答

在Windows中,你可以使用:

const std::wstring hex = L"0x13";
const std::wstring dec = L"19";

int ret;
if (StrToIntEx(hex.c_str(), STIF_SUPPORT_HEX, &ret)) {
    std::cout << ret << "\n";
}
if (StrToIntEx(dec.c_str(), STIF_SUPPORT_HEX, &ret)) {
    std::cout << ret << "\n";
}

如果需要解释十六进制,Strtol和stringstream需要指定基数。

其他回答

你可以使用std::stringstream,这里有一个例子:

#include <iostream>
#include <sstream>
using namespace std;
string r;
int main() {
    cin >> r;
    stringstream tmp(r);
    int s;
    tmp >> s;
    cout << s;
    return 0;
}

还有另一种简单的方法:假设你有一个像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

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

从http://www.cplusplus.com/reference/string/stoi/

// stoi example
#include <iostream>   // std::cout
#include <string>     // std::string, std::stoi

int main ()
{
  std::string str_dec = "2001, A Space Odyssey";
  std::string str_hex = "40c3";
  std::string str_bin = "-10010110001";
  std::string str_auto = "0x7f";

  std::string::size_type sz;   // alias of size_t

  int i_dec = std::stoi (str_dec,&sz);
  int i_hex = std::stoi (str_hex,nullptr,16);
  int i_bin = std::stoi (str_bin,nullptr,2);
  int i_auto = std::stoi (str_auto,nullptr,0);

  std::cout << str_dec << ": " << i_dec << " and [" << str_dec.substr(sz) << "]\n";
  std::cout << str_hex << ": " << i_hex << '\n';
  std::cout << str_bin << ": " << i_bin << '\n';
  std::cout << str_auto << ": " << i_auto << '\n';

  return 0;
}

输出:

2001,太空漫游:2001和[,太空漫游]

40 c3: 16579

-10010110001: -1201

0x7f:127