簡體   English   中英

比較使用fgets和fscanf獲取的字符串

[英]compare string acquired with fgets and fscanf

我需要比較一個由fdin從stdin獲取的字符串,以及另一個由fscanf從文件中獲取的字符串(並使用fprintf寫入文件)。 我必須使用這兩個函數從stdin和文件中讀取。 我怎么能這樣做? 因為我看到fgets也存儲“\\ 0”字節,但是fscanf沒有。

這是代碼:

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

typedef struct asd {
    char a[20];
    char b[20];
} struttura;


void stampa_file() {
struttura *tmp = NULL;
struttura *letto = NULL;
FILE *file;

tmp = (struttura *)malloc(sizeof(struttura));
letto = (struttura *)malloc(sizeof(struttura));
file = fopen("nuovoFile", "r");
printf("compare:\n");\
fgets(letto->a, sizeof(letto->a), stdin);
fgets(letto->b, sizeof(letto->b), stdin);
while(!feof(file)) {
    fscanf(file, "%s %s\n", tmp->a, tmp->b);
    printf("a: %s, b: %s\n", tmp->a, tmp->b);
    if(strcmp(letto->a, tmp->a) == 0 && strcmp(letto->b, tmp->b)) {
        printf("find matching\n");
    }
}
free(tmp);
free(letto);
}

int main() {
struttura *s = NULL;
FILE *file;

s = (struttura *)malloc(sizeof(struttura));

file = fopen("nuovoFile", "a+");
printf("");
fgets(s->a, sizeof(s->a), stdin);
printf("");
fgets(s->b, sizeof(s->b), stdin);
fprintf(file, "%s%s\n", s->a, s->b);
fclose(file);
stampa_file();

free(s);
return 0;
}

這里有很多潛在的問題,取決於你想要做什么

  • fgets讀取一行(直到並包括換行符),而fscanf(.."%s"..)讀取由空格分隔的標記。 完全沒有相同的東西。

  • fscanf(.."%s"..)不檢查您要寫入的緩沖區的邊界。 你真的想要fscanf(.."%19s"..)來確保它不會向你的20字節緩沖區寫入超過20個字節(包括NUL終結符)。

  • while(!feof(fp))幾乎總是錯的。 feof沒有告訴你,如果你在文件的末尾,它會告訴你是否已經嘗試讀取文件的末尾。 因此,如果您只是讀到文件的末尾並且尚未讀過它,則feof將返回false,但下一次讀取將失敗。

  • 你真的想檢查fscanf的返回值,以確保它讀取你想要讀取的內容(並實際上向輸出緩沖區寫了一些內容。)結合上面的內容,這意味着你可能希望你的循環類似於:

     while (fscanf(fp, "%19s%19s", tmp->a, tmp->b) == 2) { : 

我怎么能這樣做? 因為我看到fgets也存儲“\\ 0”字節,但是fscanf沒有。

我剛剛閱讀了fscanf的文檔並測試了它,這很好用:

#include <stdio.h>

int main()
{
    char str[100] = { 1 }; // intentionally initialized to nonzero junk
    fscanf(stdin, "%s", str);
    if (strcmp(str, "H2CO3") == 0)
        printf("This is me\n");
    else
        printf("This is not me\n");
    return 0;
}

使用%s傳遞時,scanf或fscanf會終止換行符或空格字符串上的字符串。 fgets一直等到\\ n。

因此,如果你打電話

fscanf(stdin, "%s", str);

vs

fgets(str);

並且文件包含“Hello there”

fscanf只包含“Hello”,其中fgets將返回整個字符串

暫無
暫無

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

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