Thread: Fill float array with the float numbers from a .txt file

  1. #1
    Registered User
    Join Date
    Aug 2021

    Exclamation Fill float array with the float numbers from a .txt file

    I have a dynamic 2D float array and a file with both strings, integers(number of floats in the line) and float numbers. I got the number of lines from the first line on the file and the number of columns from the highest of the integers in the line.
    John 3 5.5 89.5 30.67 0.00
    Mary 4 78.9 67.4 67.3 9.0 0.00

    The number of lines is the one on the file + 1 because the last line is supposed to be empty and the number of columns is the highest of the integers after the names + 1 (5 in this case) because the 0.00 marks the end of each line. How do I load only the floats into memory?

    I've tried different types of loops with fgets and strtok like

    for(i = 0; i < num_lines; i++){
             fgets(buf,1000, arq);
             fscanf(aux, "%s ", &name);
             fscanf(aux, "%d ", &col);
            for(j = 0; j < num_columns; j++){
                fscanf(arq, "%f ", &M[i][j]);

    num = atof(strtok(NULL, " "));
     M[i][j] = num;
    instead of the fscanf(arq, "%f ", &M[i][j]);

    But it doesn't work, I get either an array full of 0.00 or -0.00 or at most random numbers between them. I need it to be an array of floats instead of strings because other functions will use the lines for math operations.

    Last edited by tylerdji; 08-28-2021 at 08:53 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    You could do something like this.
    #include <stdio.h>
    int main() {
      char line[] = "John 3 5.5 89.5 30.67 0.00\n"; // replace with fgets
      char name[100];
      char *linePtr = line;
      int pos;
      linePtr += pos;
      double value;
      while ( sscanf(linePtr,"%lf%n",&value,&pos) == 1 ) {
        printf("Scanned value=%f\n",value);
        linePtr += pos;
      return 0;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 01-29-2014, 05:17 PM
  2. Static float array in header file
    By kotoko in forum C++ Programming
    Replies: 5
    Last Post: 06-15-2009, 11:54 AM
  3. Replies: 8
    Last Post: 07-08-2005, 09:12 AM
  4. Unresolved external 'convert(float, float)'
    By Ipsec Espah in forum C++ Programming
    Replies: 4
    Last Post: 05-21-2003, 10:08 AM
  5. read float array from file
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 07-02-2002, 04:20 AM

Tags for this Thread