Assign values to a 2d vector in c ++ [closed]

0

I'm trying to assign values to a 2d vector in c ++ This is how it is defined, where rows and columns are integers defined.

vector < vector <int>> vec(filas , vector <int> (columnas));

what I want to assign to each space of the vector are characters that are in a pbm file that clearly contains only ones and zeros

char i;
FILE* file;
file = fopen("archivo.pbm", "r");

then in this way I am passing values to each of its "boxes",

for (int h=0; h<filas; h++){
    for (int j=0; j<columnas; j++){ 
        while((i=fgetc(file))!=EOF){
            vec[h][j] = i;
        }
    } 
}

but then when printing on the screen the values of the vector, it turns out that it only contains zeros and curiously in vec [0] [0], stores a '10'

for (int h=0; h<filas; h++){
        for (int j=0; j<columnas; j++) 
            cout << vec[h][j];
    cout <<endl; 
}

fclose(file);

if someone could tell me why by assigning the values in this way, it does not turn out in advance thank you very much!

vec[h][j] = i;
    
asked by jarscs 07.07.2018 в 10:02
source

1 answer

1

-All the times that you equal i to vec you are overwriting their value, because of the while the final value granted and the one to be printed on the screen is the last of the text file (for that reason you have all the values repeated). You should change the getc () function to fscanf () which reads until you find the next 'strange' character and delete the while.

The code would stay like this:

for (int h=0; h<filas; h++){
    for (int j=0; j<columnas; j++){ 
         int number;
         fscanf(file,%d,&number);
         vec[h][j] = number;
    } 
}
    
answered by 10.07.2018 в 23:50