【问题标题】:fscanf string from file文件中的 fscanf 字符串
【发布时间】:2021-12-27 14:44:14
【问题描述】:

我有我的代码应该读取的文件“student_read.txt”。

该文件包含以下内容:

3872187

约翰·多伊

21

然后它将打印在 print_student 函数中看到的信息。但似乎当它使用 fscanf 从文件中读取时,它会检测到 John 和 doe 之间的空格作为输入,这使得输出是。

学生编号:3872187

全名:约翰

年龄:母狗

我该怎么做才能让它打印输出:

学生编号:3872187

全名:john doe

年龄:21

#include <stdio.h>
#include <string.h>
#define STRING_LENGTH 100
//Struct with alias student_t that contains student information.
typedef struct student_t{
    char studentId[STRING_LENGTH];
    char studentName[STRING_LENGTH];
    char studentAge[STRING_LENGTH];
}student_t;

//function for printing the student information
void print_student(struct student_t student){
    printf("\nStudent id: %s\n", student.studentId);
    printf("Name: %s\n", student.studentName);
    printf("Age: %s\n", student.studentAge);

}

int main() {
    //Use the defined struct to crate an instance of Student
    struct student_t student;

    //Zero out all the memory of the struct instance
    memset(&student, 0, sizeof(student));

    //selecting option
    int option;
    printf("Choose an option");
    scanf("%i", &option);


    switch(option){
        case 1:{
            FILE* read = fopen("student_read.txt", "r");

            fscanf(read, "%s", &student.studentId);
            fscanf(read, "%s", &student.studentName);
            fscanf(read, "%s", &student.studentAge);




            print_student(student);


        }
        break;
        case 2:{
            //Asks for student_t id
            printf("\nStudent id: ");
            scanf("%s", &student.studentId);

            //getchar(); is used to prevent newline in input of fgets function.
            getchar();

            //Asks for full name (strcpy since datatype = string)
            char name[STRING_LENGTH] = {0};
            printf("\nFull name: ");
            fgets(name, STRING_LENGTH, stdin);
            name[strlen(name)- 1] = 0;
            strcpy(student.studentName, name);


            //Asks for age
            printf("\nAge: ");
            scanf("%s", &student.studentAge);

        }
        break;
        case 3:{
            printf("Program closing");
        }
        break;

        default:
            printf("Invalid Option... Try again");


    }
/*





    FILE* write = fopen("student_write.txt", "w");

    if (read==0){
        printf("failed to open file\n");
        return -1;
    }

    fclose(read);
    fclose(write);
*/

    return 0;
}

【问题讨论】:

  • 不要将scanfgetcharfgets 混为一谈,您将永远追逐自己的尾巴。使用fgets 读取每一行,然后使用sscanf 处理它。
  • 另外,fscanf(read, "%s", &amp;student.studentName); 不会读取示例名称“John Doe”。它将停在空间。 (并删除带有字符串类型的&amp;。)

标签: c clion


【解决方案1】:

您可以使用fgets 代替fscanf。此函数将读取字符,直到找到换行符或文件结尾,因此它不会在空格处停止。

编辑:如果你需要强制使用fscanf,你可以查看这个回复:R: Can fscanf() read whitespace?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 2012-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多