繁体   English   中英

文件中的 fscanf 字符串

[英]fscanf string from file

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

该文件包含以下内容:

3872187

约翰·多伊

21

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

学生证:3872187

全名:约翰

年龄:母鹿

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

学生证:3872187

全名:约翰·多伊

年龄: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;
}

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

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

暂无
暂无

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

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