Convert char array to int C ++ array

I'm having trouble converting a char array read from a 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]);
}
+3
source share
4 answers

This is because it atoireceives a string with a null separator, while you pass it a pointer to one char(both essentially char *, but the intent and use are different).

Change the call atoitoiPatrons[i] = vectorPatron[i] - '0';

Alternatively, you can delete the array vectorPatrons, just read it single-handedly charin the first loop and then assign an appropriate place in the array iPatrons.

+2
source

++, C. :

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"));
+4

, atoi, ( , \0). :

for(i=0;i<67;i++){
    iPatrones[i] = int(vectorPatron[i] - '0');
    printf("%d",iPatrones[i]);
}

. , , , , . ? , ( , ):

for(i=0;i<67;i++){
    fscanf(archivo, "%d", &iPatron[i]);        
}
+1

. a char int int. BAD_RETURN = 10, "0" "9". cplusplus.com.

int CharToInt(char ch)
{
    return((ch >= '0' && ch <= '9') ? ch - '0' : BAD_RETURN);
}

This is my own function that works in the VS2015 compiler. Define an int array and initialize it to 0s. Pass this int array along with the char prototype array to the following function. This function converts the char array to an int array using the CharToInt function:

void copyCharArrToIntArr(char from[MAX], int to[MAX]) 
{
    for (int i = 0; i < MAX; i++)
        to[i] = CharToInt(from[i]);
}

This approach will work with vectors. Instead of MAX, use a i < yourVector.size()for-loop condition for it.

0
source

Source: https://habr.com/ru/post/1749887/


All Articles