Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

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("%s
", 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("%s
", student[k].name);
      fclose ( file );
  }

}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #read #file #line #line #struct
ADD COMMENT
Topic
Name
7+8 =