Answers for "read a file line by line c++ struct site:stackoverflow.com"

C++
0

read a file line by line c++ struct site:stackoverflow.com

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    char name[100];
    int age;
    float height;
} PERSON;

int
main()
{
    PERSON *X = NULL;
    FILE *f;
    int i;
    PERSON *p;
    size_t count = 0;
    size_t alloc = 0;

    f = fopen("filename.txt", "r");

    while (1) {
        if (count >= alloc) {
            alloc += 100;
            X = realloc(X,sizeof(PERSON) * alloc);
        }

        p = &X[count];

        if (fscanf(f, "%s%d%f", p->name, &p->age, &p->height) == EOF)
            break;

        ++count;
    }

    fclose(f);

    // trim the array to what was actually used
    X = realloc(X,sizeof(PERSON) * count);

    p = X;
    for (i = 0;  i < count;  i++, p++)
        printf("%sn%d n%fn", p->name, p->age, p->height);

    return 0;
}
Posted by: Guest on January-30-2022
0

read a file line by line c++ struct site:stackoverflow.com

#include <stdio.h>

// struct person with 4 fields
    struct person
    {
        char name[100];
        char address[100];
        char IDnumber[20];
        int  age;
    };

int main()
{
   FILE *file = fopen ("personout.txt","r");
   // declares an struct array to store data
   struct person student[10];

   int k=0;

   if ( file != NULL )    
   {
       char line [ 128 ]; /* or other suitable maximum line size */
       while ( fgets ( line, sizeof line, file ) != NULL ) /* read a line */
       {
           // Returns first token
           char* token = strtok(line,",");

          // Keep printing tokens while one of the
          // delimiters present in str[].
          while (token != NULL) {
              k=0;
           // countword++;
              printf("%sn", token);

              switch (k) {
              case '1':
                  student[k].name==token;
              case '2':
                  student[k].address==token;
              case '3':
                  student[k].IDnumber==token;
              case'4':
                  student[k].age==token;
              default:
                  break;
              }

              k++;

              // put the values to array
              token = strtok(NULL, ",");
          }
      }
      printf("%sn", student[k].name);
      fclose ( file );
  }

}
Posted by: Guest on January-30-2022

Code answers related to "read a file line by line c++ struct site:stackoverflow.com"

Browse Popular Code Answers by Language