【问题标题】:how to change type of value char array to int in c++? [duplicate]如何在 C++ 中将值 char 数组的类型更改为 int? [复制]
【发布时间】:2014-03-09 08:32:46
【问题描述】:

我是 CPP 的新手。

我正在尝试创建小型控制台应用程序。

我的问题是,有没有办法将 char 数组更改为整数...?!

例如:

char myArray[]= "12345678"int = 12345678 ...?!

tnx

【问题讨论】:

  • atoi, sscanf, stringstream...
  • @yasouser 问题在于 C++,而不是 C。Mat 的评论是正确的

标签: c++ arrays char int


【解决方案1】:

您不会“更改”类型。你想要的是创建一个特定类型的对象,使用另一个类型的对象作为输入。

由于您是 C++ 新手,您应该知道不建议将数组用于字符串。使用真正的字符串:

std::string myString = "12345678";

那么你有两种标准的方法来转换字符串,这取决于你使用的 C++ 版本。对于“旧”C++,std::istringstream:

std::istringstream converter(myString);
int number = 0;
converter >> number;
if (!converter) {
    // an error occurred, for example when the string was something like "abc" and
    // could thus not be interpreted as a number
}

在“新”C++ (C++11) 中,您可以使用std::stoi

int number = std::stoi(myString);

带有错误处理:

try {
    int number = std::stoi(myString);
} catch (std::exception const &exc) {
    // an error occurred, for example when the string was something like "abc" and
    // could thus not be interpreted as a number
}

【讨论】:

  • 对于一个刚接触 C++ 的人来说,有很多东西要理解
  • @yasouser:是的,但他还应该做什么?如果他目前正在使用 char 数组,他无论如何都必须学习字符串。
  • 请看我更新的答案。
【解决方案2】:

使用boost::lexical_cast:

#include <boost/lexical_cast.hpp>

char myArray[] = "12345678";
auto myInteger = boost::lexical_cast<int>(myArray);

【讨论】:

  • 对于 C++ 新手,您可能应该向他指出如何获得 Boost。
  • 你谷歌“boost c++”,点击第一个结果,然后点击“Get Boost”。
  • @yasouser,您是否认为刚接触 C++ 与刚接触互联网和计算机的思维一样?
【解决方案3】:

atoi 函数正是这样做的。

【讨论】:

  • 它对某些输入有未定义的行为,但没有失败指示。
  • @David:atoi 无法区分“0”和“x”。
  • 对于一个非常简单的问题,很高兴给出一个非常简单的答案。是的,我们可以继续讨论细微差别。
  • 这不是细微差别。 atoi() 是一个严重损坏的函数,IMO。
【解决方案4】:

除了带有符合 C++11 标准的编译器的 atoi() 之外,您还可以使用 std::stoi()

【讨论】:

  • 由于错误处理,应该避免 atoi()。 std::to_string() 与他想要的相反......
  • @ChristianHackl:感谢您的指出。我的意思是指stoi。
猜你喜欢
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
  • 2017-02-19
  • 2021-09-02
  • 1970-01-01
  • 2013-01-10
  • 1970-01-01
  • 2016-02-20
相关资源
最近更新 更多