簡體   English   中英

C-sscanf在讀取文件后給我錯誤的輸出

[英]C - sscanf giving me wrong output after reading file

我正在嘗試從C中的文本文件中讀取一行,但是輸出表示錯誤。 我認為我的代碼中的分隔符做錯了。 有人可以幫忙嗎?

文本:

你好,世界,1,2,再見

輸出:

你好世界12576 117453344再見

typedef struct structure {
    char hello[25];
    char world[25];
    int num1;
    int num2;
    char bye[25];
} Hello;

主要:

#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include "structure.h"

using namespace std;

int main(int argc, char **argv) {
    char line[25];
    FILE *fp;
    fp = fopen("text.txt", "r");
    Hello c;  

    while (fgets(line, sizeof(line), fp) != NULL) {
        sscanf(line, "%[^','],%[^','],%[^','],%[^','],%s",
               c.hello, c.world, &c.num1, &c.num2, c.bye);
    }

    printf("%s %s %d %d %s", c.hello, c.world, &c.num1, &c.num2, c.bye);   

    return 0;
}

不要使用%[^',']來讀取整數。 應該使用%d並且也要忽略sscanf中字符串',' ,請使用說明符%[^,]

並檢查其返回值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM