如何从文件读取字符直到空格并将其存储为一个字符串(c)? [英] How to read characters from a file until a space and store that as one string (c)?

查看:586
本文介绍了如何从文件读取字符直到空格并将其存储为一个字符串(c)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在空格之前从文件中的一行读取所有信息并将其存储为字符串,该怎么办?

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?

文件示例:

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

感谢您的帮助,我也愿意尝试其他方法.我尝试使用长度为i的fgets,该长度等于在上一个while循环中找到的空格之前的字符数,但这会在我想要的区域之后直接打印该部分.

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.

推荐答案

从文件读取一直到fgetc的第一个space字符都没有问题,但是,存在以下问题:

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

当您调用fgetc(grades) != ' '时,将从grades中读取一个字符,然后 file-position-indicator 前进到下一个字符.因此,当您在if语句中调用fgetc时,您将读取一个字符,然后前进 file-position-indicator 以准备读取下一个字符.然后,如果在if语句(currChar = fgetc(grades);)的正文中再次调用fgetc,则将读取文件中的 second 字符.从您的问题看来,很明显,您的意图不是跳过一个字符,而是从下一个开始阅读.

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.

当您使用任何面向字符输入功能(例如getcharfgetc等)读取输入时,您要负责三件事:(1)确保您自己不要尝试向存储变量中写入超出其容纳范围的字符; (2)检查您希望停止阅读的任何前哨或终止字符;和(3)检查您尚未到达输入流的末尾.

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

注意:当您停止阅读任何字符时,下一次阅读将在输入流中的下一个字符处继续进行.因此,如果您想从下一个字符以外的其他字符开始读取,则需要清空所有剩余字符(在该行等).另请注意,使用fopen打开文件时,应在继续从文件中读取文件之前确认该打开是否确实有效.

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.

输入

$ cat grades.txt
Homeroom grades are include below

输出

$ ./bin/fgetc_grades

 className: Homeroom

希望这会帮助您入门,如果还有其他问题,请告诉我.

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

这篇关于如何从文件读取字符直到空格并将其存储为一个字符串(c)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆