繁体   English   中英

如何使用带有整数和字符串的文本文件中的fscanf和fgets?

[英]How to use fscanf and fgets from a text file with ints and strings?

示例文件:

School Name (with spaces)
FirstNameofStudent StudentID
School Name2 (with spaces)
FirstNameofStudent2 StudentID2
School Name3 (with spaces)
FirstNameofStudent3 StudentID3

在第一行使用fgets之后,我似乎无法弄清楚该怎么做。

如果studentID使用,我可以使用fgets轻松获得学校名称,而使用fscanf可以轻松获取第二行,然后使用atoistudentID转换为int。

但是,如何将fgetsfscanf结合在一起?

扫描的信息将被放入一个数组中。

在介绍解决方案之前,我想指出一个数组只能有一个类型。 您不能将整数存储在字符数组中。

这意味着,如果您希望所有这些信息都存储在单个2D数组中,则需要将ID存储为字符串。 然后,如果您需要将其作为整数,则一旦检索它,就需要在其上使用atoi

现在,将两者结合起来,您需要在条件中包含带有fgets的while循环,以便检索第一行。 像这样:

while(fgets(schoolname, 255, fp) != 0){ ... }

这将继续检索行,直到失败或到达EOF。 但是,您想在第二行中使用fscanf ,为此,您需要这样的一行:

fscanf(fp, "%s %s\n", name, id);

这意味着,从当前点开始,有两个字符串用空格和换行符分隔。 将两个字符串分别存储在nameid ,并在换行符处添加一个空格。

关键在于换行,​​如果您不这样做,则下次fgets运行时,它将仅在该行上找到一个换行。

至于将元素存储在数组中,则需要2D字符串数组。 为此,您可以将其固定或动态地进行。 对于固定而言,这很容易,只需像char students[3][3][80]这样的一行,然后将内容存储在其中,而对于动态,则需要使用带有变量的内存分配,指针等liks char ***students

这是我用来解决您的问题的代码,尽管我建议您也尝试自己做,以解决问题:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(){
    FILE *fp = fopen("ex.txt", "r");

    if(fp == 0) exit(-1);

    char ***students;

    // Used to check how many students there are
    int studentno = 0;

    // Init students array
    // So far it means 1 ROW, with 3 COLUMNS, each of 80 CHARACTERS
    students = calloc(studentno+1, 3 * 80);

    // Temporary variables for storage
    char schoolname[80];
    char name[20];
    char id[10];

    int i = 0;

    while(fgets(schoolname, 255, fp) != 0){
        studentno++;

        // Retrieve name and id from second line
        fscanf(fp, "%s %s\n", name, id);

        // Cut off newline left from fgets
        schoolname[strlen(schoolname)-2] = 0;

        // Allocate memory for new members of array
        students[i] = malloc(3 * 80);
        students[i][0] = malloc(80);
        students[i][1] = malloc(80);
        students[i][2] = malloc(80);

        // Copy strings received into array
        strcpy(students[i][0], schoolname);        
        strcpy(students[i][1], name);
        strcpy(students[i][2], id);

        // Resize students array for additional students
        students = realloc(students, (size_t) (studentno+1) * 3*80);

        i++;
    }

    // Check students are stored correctly
    for(int i = 0; i < studentno-1; i++){
        printf("%s - %s - %s\n", students[i][0], students[i][1], students[i][2]);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM