How to read characters from a file until a space and store that as one string (c)?

MariaCodesOK picture MariaCodesOK · Nov 28, 2015 · Viewed 26.8k times · Source

I need to read all the information from a line in a file before a space and store it as a string, how do I do that?

File example:

Biology A 4.0
Tennis B 1.0

etc (I need the letter and number later and I know how to store them fine, just the dang string is giving me trouble)

So far I have

int main (void)
{
    FILE* grades;
    char className[10];
    char currChar;
    int i = 0;

    grades = fopen("grades.txt", "r");
    if (fgetc(grades) != ' ')
    {
        currChar = fgetc(grades);
        className[i] = currChar;
        i++;
    } 

    /* what I want to happen here: if a character is not a space, it is
        appended to className. I thought if i was the position in the array,
        I could add in one character at a time
    */
    printf("%s", className); // check to make sure it worked
}

what the result is: the symbol that looks like a ? in a hexagon

Thanks for any help, I'm open to trying other ways too. I tried using fgets with the length i equal to the number of characters before a space found in a previous while loop, but that printed the part directly after the area I wanted.

Answer

loxxy picture loxxy · Nov 28, 2015

Why not just use fscanf ?

Something like :

#include <stdio.h>

int main (void)
{
    FILE* grades;
    char className[10];
    char grade;
    float marks = 0;

    grades = fopen("grades.txt", "r");

    while(fscanf(grades,"%s %c %f", className, &grade, &marks)>0) {
        printf("%s %c %f\n", className, grade, marks); 
    }
}