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

Asked

Viewed 20,308 times

3

I want to know how to read a file in c++. The first line has the size of the matrix and the other one has the elements of the matrix. Each element is separated by a blank space, there may be negative numbers. Lines end with \n.

I did it but it hasn’t worked out so 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");

}
  • If you’re going to use this to work and not to study, learn how to work with a database (MS Windows: SQL, Cross-Platform: Mysql (Oracle). http://msdn.microsoft.com/pt-br/library/ktheed7h(v=vs.90). aspx (translation option above) and http://dev.mysql.com/doc/refman/5.1/en/connector-cpp-info.html

  • @Lucashenrique for study purposes only

  • 3

    @Lucashenrique I don’t see how Bds would be a good alternative to a problem involving matrix manipulation.

  • @C.E.Gesser does not mean matrix manipulation, but data search. It is usually done in binary... Learning to deal with databases is very important :)

  • 3

    It is certainly important, just as it is important to know the best tool for each problem. By the description probably after reading the matrix will be necessary some kind of manipulation, and for that it is good to have everything in memory even.

  • @C.E.Gesser, I’m going to have to parallelize the Jacobi method by calculating the inserted matrix

Show 1 more comment

2 answers

5


#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
}
  • Why file >> size?

  • 1

    Because the first thing in the file is the size of the matrix, at least that’s what’s in the statement.

  • Legal :) Thank you.

  • @C.E.Gesser, not taking the value of the first line, debugging shows error, I’m using visual studio

  • 1

    The archive matriz.txt is in the folder from where you are running the executable?

  • I’m using the visual studio, by fopen was not, was in a different place from the executable, because the same created it in a different dir. I’ll put txt on the same level as the executable.

  • That was probably your mistake at first

  • It is not a problem for the file to be at the same level of the executable, I put, but with the old code the reading was done.

  • 1

    I did a test here with a small 2x2 matrix and it worked. But I ended up finding a problem in my code that made him read an extra element, I fixed it. If the problem continues, I think we’ll need you to show an example of the matrix file, just in case.

  • ok, but it’s a file that the first line has a number and line break, second line numbers separated by white space.

  • I found the answer in this link, now I need to work to get the other lines.

  • @C.E.Gesser This way it is much faster to read file...

  • Good that it worked out, good luck on the rest of the problem now!

Show 8 more comments

3

When it comes to C++ you can use the std::fstream and the operators reading from 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 the operator>> returns the stream itself (the file), and tests the stream as a boolean value (if (!file)) returns if an error occurred on last read or write. Hence the language if (!(file >> var)) {/*erro*/}.

  • the operator >> is binary?

  • No. It reads formatted values such as 56 or -874.

  • 2

    The operator >> has two features in C++: bitwise shift right and "get-from" stream. Similarly, there is the operator << that does the opposite operations. In C++ these operators were overloaded (yes, in C++ operators can also be overloaded) to have these specific functionalities in streams.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.