简体   繁体   English

如果一个字符串是一个字符数组,你如何将它转换成一个整数数组

[英]If a string is an array of char, how do you convert it into an array of interger

I kept getting an error with this loop.我不断收到这个循环的错误。 If there are something i missed, please help.如果我遗漏了什么,请帮忙。 Thank You!谢谢你!

int main(){
 string hasil;
 int cod[5];
 hasil = "99999";

 for(int i = 0; i < 5; i++){
     cod[i] = stoi(hasil[i]);
 }

 for(int i = 0; i < 5; i++){
     cout << cod[i] + 1;
 }

stoi is for converting entire strings to integers, but you're only giving it single characters. stoi用于将整个字符串转换为整数,但您只给它单个字符。

You could either build strings from each character like so:您可以像这样从每个字符构建字符串:

cod[i] = std::stoi(std::string(1, hasil[i])); // the 1 means "repeat char one time"

Or calculate the actual integer yourself using a bit of ascii math (assuming everything is a valid digit):或者自己使用一点 ascii 数学计算实际整数(假设所有数字都是有效数字):

cod[i] = hasil[i] - '0'; // now '0' - '0' returns 0, '5' - '0' returns 5, etc...

std::stoi() takes a std::string , not a char . std::stoi()需要一个std::string ,而不是一个char But std::string does not have a constructor that takes only a single char , which is why your code fails to compile.但是std::string没有接受单个char的构造函数,这就是您的代码无法编译的原因。

Try one of these alternatives instead:请尝试以下替代方法之一:

cod[i] = stoi(string(1, hasil[i]));
cod[i] = stoi(string(&hasil[i], 1));
string s;
s = hasil[i];
cod[i] = stoi(s);
char arr[2] = {hasil[i], '\0'};
cod[i] = stoi(arr);

The below complete working program shows how you can achieve what you want:以下完整的工作程序显示了如何实现您想要的:

#include <iostream>

int main(){
 std::string hasil;
 int cod[5];
 hasil = "99999";

for(int i = 0; i < 5; ++i)
{
    cod[i] = hasil[i] - '0';
}

 for(int i = 0; i < 5; i++){
     std::cout << cod[i];
 }
 
 return 0;
}

The output of the above program can be seen here .上面程序的输出可以在这里看到。

std::stoi only accpet std::string or std::wstring as an argument type. std::stoi只接受std::stringstd::wstring作为参数类型。 But hasil[i] is a char但是hasil[i]是一个char

In C++, '0' to '9' is guarantee to be ascending in ACSII values, so, you can do this:在 C++ 中, '0''9'保证在 ACSII 值中升序,因此,您可以这样做:

cod[i] = hasil[i] - '0';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM