Home > Enterprise >  If a string is an array of char, how do you convert it into an array of interger
If a string is an array of char, how do you convert it into an array of interger

Time:10-31

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;
 }

CodePudding user response:

stoi is for converting entire strings to integers, but you're only giving it single characters.

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):

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

CodePudding user response:

std::stoi() takes a std::string, not a char. But std::string does not have a constructor that takes only a single char, which is why your code fails to compile.

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);

CodePudding user response:

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.

CodePudding user response:

std::stoi only accpet std::string or std::wstring as an argument type. But hasil[i] is a char

In C , '0' to '9' is guarantee to be ascending in ACSII values, so, you can do this:

cod[i] = hasil[i] - '0';
  •  Tags:  
  • c
  • Related