Convert each digit from number saved in string to array of int

后端 未结 2 1442
不思量自难忘°
不思量自难忘° 2021-01-28 00:50

I\'m writing this project on DFA and i want to save and covert each digit of an integer saved as a string to an int array.This is the code from the function responsible for tha

相关标签:
2条回答
  • 2021-01-28 01:29

    c_str() doest not work because after calling at(i) you've got a char not a string. I suggest you to use:

    temp_final[i]=final_states.at(i) - '0';
    

    Here you take an ASCII code for a char symbol and when you subtract a '0' you get exectly an int you need, because all the digits go in order in ASCII table.

    0 讨论(0)
  • 2021-01-28 01:41

    The atoi() function wants a const char*, you cannot call .c_str() with the result of .at(i) which is actually a char& value.

    Just fix your assignment line to

     temp_final[i] = int(final_states[i]) - int('0');
    

    Though you also might check if you really have a digit there, before putting it into your result array:

     if(std::isdigit(final_states[i])) {
         temp_final[i] = int(final_states[i]) - int('0');
     }
     else {
         // Skip, or throw error ...
     }
    
    0 讨论(0)
提交回复
热议问题