如何在c ++中将值char数组的类型更改为int?

Moh*_*uli 0 c++ arrays int char

我是CPP的新手.

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

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

例如:

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

TNX

Chr*_*ckl 6

你不"改变"一种类型.你想要的是创建一个特定类型的对象,使用另一种类型的对象作为输入.

由于您不熟悉C++,因此您不应该知道不建议使用数组作为字符串.使用真正的字符串:

std::string myString = "12345678";
Run Code Online (Sandbox Code Playgroud)

然后,您有两种标准方法来转换字符串,具体取决于您使用的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
}
Run Code Online (Sandbox Code Playgroud)

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

int number = std::stoi(myString);
Run Code Online (Sandbox Code Playgroud)

有错误处理:

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
}
Run Code Online (Sandbox Code Playgroud)