tags:

views:

81

answers:

3

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]);
}
+2  A: 

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.

abyx
A: 

I believe you cannot use the atoi function since it needs an string (array of chars terminated by the \0 character). Why dont you simply do:

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

Note: i do not know how the source file looks like, so maybe the error is there. How exactly are those numbers stored in the file? Maybe you could use (if they are stored as number separated by space):

for(i=0;i<67;i++){
    fscanf(archivo, "%d", &iPatron[i]);        
}
PeterK
`int(vectorPatron[i] - '0')` . I smell syntax error.
J-16 SDiZ
@ J-16: I thought int(vectorPatron[i] - '0') was the same as (int)(vectorPatron[i] - '0') in c++, or is there some other syntax error here?
shuttle87
There is nothing wrong with that statement. As shuttle87 said, it has the same meaning as (int)(vectorPatron[i] - '0').
PeterK
Yes, actually I`ve forgotten to say that the file is like this:11111100011000111111
Yadira Suazo
+2  A: 

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"));
Jerry Coffin
You can replace your `to_int` functor with `int to_int(char c) { return c - '0'; }`.Either way, have a +1.
utnapistim