Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

C programming: how to store text file data in array?

For example, my text file has following format:

StudentID FirstName

1001 Adam

1002 Taylor

1008 Kelly

1005 Ryan

4 Answers

Relevance
  • 1 decade ago
    Favorite Answer

    Basically:

    1) Open the file (fopen)

    2) Loop through the file reading the lines (fgets)

    3) For each line, find the space character (strchr)

    4) Replace the space with a 0 to separate the ID and name.

    5) Copy/assign a string for the ID starting from the beginning of the line read.

    6) Copy/assign a string for the first name starting one character after the 0 you placed in.

    If you need more help, ask questions about the specific parts giving you trouble.

    Here's the tricky part:

    char mystring[]="howdy person";

    char *first, *second;

    char *space=strchr(mystring, ' '); /* find the space */

    if(space==NULL) /* no space? */

    CallSomeError();

    *space=0; /* change space to separator */

    first=strdup(mystring); /* copy first part of string */

    second=strdup(space+1); /* copy after separator */

    This chunk of code takes a pointer to a string with two words separated by a space (called 'mystring') and splits it at the space, allocating new strings 'first' and 'second' to hold everything before and everything after the space.

  • Anonymous
    1 decade ago

    A 2 dimensional array array of char. Or an array of a data type that has a short and a char.

  • 1 decade ago

    Here is the algorithm for it:

    Read each string by line

    calculate it's size

    allocate memory for it

    and store

  • ?
    Lv 4
    5 years ago

    truly, you are able to desire to apply C++ streams: operators '>>' and '<<' to place in writing to and learn from the record. inspite of the reality that i write in C++ for an prolonged time, for record enter/output i despite if want good previous consumer-friendly C learn/write and fscanf/fprintf. you are able to desire to apply any of those 2 pairs with the comparable result.

Still have questions? Get your answers by asking now.