How to read a text file and get the values as integers?

2

I want to know how to read a file in c ++. The first row has the size of the array and in the rest has the array elements. Each element is separated by a space, and there may be negative numbers. Rows end with \n .

I did this but it has not worked very well.

int main() {

    FILE *file = NULL;
    int *array = NULL;
    int matrixSize = 0;
    int arraySize = 0;
    char linha[255];

    fopen_s(&file, "matriz.txt", "rt");
    rewind(file);
    fscanf_s(file, "%d", &matrixSize);
    printf("%d", matrixSize);

    arraySize = matrixSize * matrixSize;

    alocateArray(&array, arraySize);
    cleanArray(array, arraySize);

    int i = 0;

    while(!feof(file)) {

        fgets(linha, 255, file);
        char *valores = strtok(linha, " ");

        while(valores != NULL) {
            //array[i++] = (int) valores;
            printf("%s", valores);
        }
    }

    fclose(file);

    system("PAUSE");

}
    
asked by anonymous 09.02.2014 / 16:39

2 answers

4
#include <fstream>
#include <vector>

int main() {
  std::ifstream file("matriz.txt");
  unsigned size;
  file >> size; 

  if (!file) {
    //erro durante leitura
  }

  std::vector<int> matrix;
  matrix.reserve(size*size);

  while (true) {
    double value;
    if (!(file >> value)) {
      break;
    }
    matrix.push_back(value);
  }

  if (matrix.size() != size*size) {
    //erro durante leitura
  }
  //usa matriz
}
    
09.02.2014 / 16:51
2

In the case of C ++ you can use std::fstream and read operators of std::istream . An example:

#include <fstream>

int main() {
    std::ifstream file("matriz.txt");
    if (!file) {/* Falhou em abrir o arquivo */}

    int size;
    if (!(file >> size)) {/* Falhou em ler o primeiro valor */}

    int* matriz = new int[size * size];
    for (int i = 0; i < size*size; ++i) {
        if (!(file >> matriz[i])) {/* Falhou em ler um dos valores */}
    }

    // Faça algo com sua matriz aqui.

    delete[] matriz;
}

A useful feature is that operator>> returns the stream itself, and testing the stream as a Boolean value ( if (!file) ) returns if an error occurred on the last read or written. Give the language if (!(file >> var)) {/*erro*/} .

    
09.02.2014 / 17:15