Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert char array to int array c++

Tags:

c++

arrays

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]);
}
like image 297
Yadira Suazo Avatar asked Feb 27 '23 20:02

Yadira Suazo


2 Answers

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"));
like image 55
Jerry Coffin Avatar answered Mar 12 '23 11:03

Jerry Coffin


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.

like image 29
abyx Avatar answered Mar 12 '23 12:03

abyx