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

独自空忆成欢 提交于 2020-06-17 04:10:07

问题


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.


回答1:


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); 
    }
}



回答2:


There is nothing wrong with reading from a file up-to the first space character with fgetc, however, there are several problems with:

if (fgetc(grades) != ' ')
{
    currChar = fgetc(grades);
    className[i] = currChar;
    i++;
} 

When you call fgetc(grades) != ' ', a character is read from grades and then the file-position-indicator is advanced to the next character. So when you call fgetc inside the if statement, you read a character and then the file-position-indicator is advanced in preparation for reading the next character. When you then call fgetc again in the body of the if statement (currChar = fgetc(grades);), you read the second character in the file. It seems rather obvious from your question, that your intent was not to skip-a-character and then begin reading with the next.

When you read input with any character-oriented-input function (e.g. getchar, fgetc, etc.) there are three primary things you are responsible for: (1) insuring you do not attempt to write more characters to your storage variable than it will hold; (2) check for any sentinel or terminating character you wish to stop the read with; and (3) checking that you have not reached the end of the input stream.

Putting those pieces together you could do something like:

#include <stdio.h>

#define MAXCN 10

int main (void)
{
    FILE* grades = NULL;            /* initialize variables */
    char className[MAXCN] = {0};
    int currChar = 0;               /* currChar is an int   */
    int i = 0;

    /* open and validate file */
    if ((grades = fopen("grades.txt", "r")) == NULL) {
        fprintf (stderr, "error: file open failed 'grades.txt'.\n");
        return 1;
    }

    /* read from grades until 1st space */
    while (i + 1 < MAXCN && ((currChar = fgetc (grades)) != ' ' && 
                              currChar != EOF)) {
        className[i++] = currChar;
    }
    className[i] = 0;   /* null-terminate */

    printf("\n className: %s\n\n", className);

    return 0;
}

Note: when you stop reading on any character, the next read will resume on the next character in the input stream. So you will need to empty any characters that remain (in the line, etc...) if you want to begin your read at any than other than the next character. Also note, when you open a file with fopen, you should validate that the open actually worked before proceeding to read from the file.

Input

$ cat grades.txt
Homeroom grades are include below

Output

$ ./bin/fgetc_grades

 className: Homeroom

Hopefully this will help you get started, let me know if you have any additional questions.



来源:https://stackoverflow.com/questions/33968157/how-to-read-characters-from-a-file-until-a-space-and-store-that-as-one-string-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!