你不"改变"一种类型.你想要的是创建一个特定类型的对象,使用另一种类型的对象作为输入.
由于您不熟悉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)