c++用什么方法把字符串(char *)解析成int?健壮和清晰的错误处理是一个加分项(而不是返回零)。


当前回答

如果你有c++ 11,现在合适的解决方案是<string>中的c++整数转换函数:stoi, stol, stoul, stoll, stoull。当给出不正确的输入时,它们会抛出适当的异常,并在底层使用快速和小型的strto*函数。

如果您被c++的早期版本所困扰,那么在实现中模拟这些函数将是向前可移植的。

其他回答

从c++ 17开始,你可以从<charconv>头文件中使用std::from_chars。

例如:

#include <iostream>
#include <charconv>
#include <array>

int main()
{
    char const * str = "42";
    int value = 0;

    std::from_chars_result result = std::from_chars(std::begin(str), std::end(str), value);

    if(result.error == std::errc::invalid_argument)
    {
      std::cout << "Error, invalid format";
    }
    else if(result.error == std::errc::result_out_of_range)
    {
      std::cout << "Error, value too big for int range";
    }
    else
    {
      std::cout << "Success: " << result;
    }
}

另外,它还可以处理其他进制,比如十六进制。

传统的C方式仍然有效。我推荐散步或散步。在返回状态和'endPtr'之间,您可以给出良好的诊断输出。它还可以很好地处理多个碱基。

你可以使用c++标准库中的a stringstream:

stringstream ss(str);
int x;
ss >> x;

if(ss) { // <-- error handling
  // use x
} else {
  // not a number
}

流状态将被设置为失败 当遇到非数字时 正在读取一个整数。

有关c++中错误处理和流的陷阱,请参阅流陷阱。

我知道三种将String转换为int的方法:

要么使用stoi(String to int)函数,要么使用Stringstream,第三种方式进行个人转换,代码如下:

1号方法

std::string s1 = "4533";
std::string s2 = "3.010101";
std::string s3 = "31337 with some string";

int myint1 = std::stoi(s1);
int myint2 = std::stoi(s2);
int myint3 = std::stoi(s3);

std::cout <<  s1 <<"=" << myint1 << '\n';
std::cout <<  s2 <<"=" << myint2 << '\n';
std::cout <<  s3 <<"=" << myint3 << '\n';

2方法

#include <string.h>
#include <sstream>
#include <iostream>
#include <cstring>
using namespace std;


int StringToInteger(string NumberAsString)
{
    int NumberAsInteger;
    stringstream ss;
    ss << NumberAsString;
    ss >> NumberAsInteger;
    return NumberAsInteger;
}
int main()
{
    string NumberAsString;
    cin >> NumberAsString;
    cout << StringToInteger(NumberAsString) << endl;
    return 0;
} 

第三种方法-但不是个人转换

std::string str4 = "453";
int i = 0, in=0; // 453 as on
for ( i = 0; i < str4.length(); i++)
{

    in = str4[i];
    cout <<in-48 ;

}

我喜欢丹的回答,尤其是因为他避免了例外。对于嵌入式系统开发和其他低级别的系统开发,可能没有适当的Exception框架可用。

增加了一个有效字符串后的空白检查…这三行

    while (isspace(*end)) {
        end++;
    }

还增加了对解析错误的检查。

    if ((errno != 0) || (s == end)) {
        return INCONVERTIBLE;
    }

这是完整的功能..

#include <cstdlib>
#include <cerrno>
#include <climits>
#include <stdexcept>

enum STR2INT_ERROR { SUCCESS, OVERFLOW, UNDERFLOW, INCONVERTIBLE };

STR2INT_ERROR str2long (long &l, char const *s, int base = 0)
{
    char *end = (char *)s;
    errno = 0;

    l = strtol(s, &end, base);

    if ((errno == ERANGE) && (l == LONG_MAX)) {
        return OVERFLOW;
    }
    if ((errno == ERANGE) && (l == LONG_MIN)) {
        return UNDERFLOW;
    }
    if ((errno != 0) || (s == end)) {
        return INCONVERTIBLE;
    }    
    while (isspace((unsigned char)*end)) {
        end++;
    }

    if (*s == '\0' || *end != '\0') {
        return INCONVERTIBLE;
    }

    return SUCCESS;
}