簡體   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