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

泄露秘密 提交于 2020-01-11 14:04:08

问题


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


int l=final_states.size();
int* temp_final;
temp_final=new int [l];
for(int i=0;i<l;i++)
{
    temp_final[i]=atoi(final_states.at(i).c_str());
}

This gives me the following mistake : request for member 'c_str' in '((DFA*)this)->DFA::final_states.std::basic_string<_CharT, _Traits, _Alloc>::at<char, std::char_traits<char>, std::allocator<char> >(((std::basic_string<char>::size_type)i))', which is of non-class type 'char'|.


So if you could tell me how to make this conversion and saving work , that would be great.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/23793198/convert-each-digit-from-number-saved-in-string-to-array-of-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!