I`m having problems converting a char array read from file to an int array. Maybe someone can help me. This is my code:
char vectorPatron[67];
int iPatrones[67];
archivo = fopen("1_0.txt", "r");
for(i=0;i<67;i++){
fscanf(archivo, "%c", &vectorPatron[i]);
printf("%c",vectorPatron[i]);
}
fclose(archivo);
for(i=0;i<67;i++){
iPatrones[i] = atoi(&vectorPatron[i]);
printf("%d",iPatrones[i]);
}
Despite using some C++ features, most of your code looks more like C. Might I recommend something more like:
struct to_int {
int operator()(char c) { return c - '0'; }
};
const int num = 67;
std::vector<char> patrons(num);
std::vector<int> patron_values(num);
std::ifstream archivo("1_0.txt");
archivo.read(&patrons[0], num);
std::cout.write(&patrons[0], num);
std::transform(patrons.begin(), patrons.end(), patron_values.begin(), to_int());
std::copy(patron_values.begin(), patron_values.end(),
std::ostream_iterator<int>(std::cout, "\n"));
That's because atoi
receives a null-delimited string, while you are passing it a pointer to a single char
(both are essentially char *
, but the intent and use are different).
Replace the call to atoi
with iPatrons[i] = vectorPatron[i] - '0';
Also, you can remove the vectorPatrons
array, simply read into a single char
in the first loop and then assign to the appropriate place in the iPatrons
array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With