c - %79[^\n] 和 %79[^\n]\n 的区别

标签 c scanf string-formatting

我有两个 C 程序。

首先:

#include <stdio.h>

int main(int argc, char *argv[]){
    float latitude;
    float longitude;
    char info[80];
    int started = 0;

    puts("data=[");
    while ((scanf("%f,%f,%79[^\n]",&latitude,&longitude, info)) == 3){
    if (started) 
        printf(",\n");
    else
        started = 1;
    if ((latitude < -90) || (latitude > 90)){
        fprintf(stderr,"Wrong latitude %f\n", latitude);
        return 2;
    }
    if ((longitude < -180) || (longitude > 180)){
        fprintf(stderr,"Wrong longitude %f\n", longitude);
        return 2;
    }

    printf("{latitude: %f, longitude: %f, info: '%s'}", latitude, longitude, info); 
    }
    puts("\n]");     

    return 0;
}

第二个:

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

int main(int argc, char *argv[]){
    char line[80];
    FILE *in = fopen("spooky.csv","r");
    FILE *file1 = fopen("ufos.csv","w");    
    FILE *file2 = fopen("disappearances.csv","w");
    FILE *file3 = fopen("others.csv","w");
    while(fscanf(in,"%79[^\n]\n",line)==1){
        if (strstr(line, "UFO"))
            fprintf(file1,"%s\n",line);
        else if (strstr(line, "Disappearance"))
            fprintf(file2, "%s\n", line);
        else 
            fprintf(file3,"%s\n",line);
    }
    fclose(file1);
    fclose(file2);
    fclose(file3);
    return 0;
}

我不明白为什么第一个代码使用指令 %79[^\n] 输出我的文件的所有行,而第二个代码仅使用此指令输出所有行 %79 [^\n]\n 如果我写 %79[^\n]

只输出一行文本

请解释一下 %79[^\n]%79[^\n] 两个代码和两个指令之间的区别

最佳答案

导致问题的不是格式说明符本身,而是它如何与其他格式说明符一起使用。

如果您阅读例如this scanf (and family) reference您会看到 "%[" 格式不会跳过前导空格,而大多数其他格式(例如 "%f").

当您在第一个程序中读取输入时,您不需要 scanf 函数来读取结束换行符(这是一个空白字符),因为下一次调用 scanf 将导致 "%f" 格式说明符在尝试读取浮点值之前跳过该换行符。

对于第二个程序,如果你有 "%79[^\n]" 那么 fscanf 将读取直到但不包括第一个换行符。然后在循环的下一次迭代中,相同的格式将尝试读取字符,直到出现换行符,但输入中的第一个字符换行符,因此实际上不会读取任何内容。

如果您添加尾随换行符(任何空白字符都可以),那么 fscanf 函数将跳过换行符,因此下一次调用 fscanf 将读取下一行正确。您可以通过在格式中使用前导 空格来完成同样的事情。 IE。而不是 "%79[^\n]\n" 你可以有
“%79[^\n]”

话虽如此,如果您想读取行,请使用 fgets反而。这就是它所做的,没有 scanf 会遇到的许多问题。

关于c - %79[^\n] 和 %79[^\n]\n 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48248277/

相关文章:

c - 选择排序程序产生不正确的输出

c - C中char*的指针问题

c - scanf() 将换行符保留在缓冲区中

c - (C) 从文本文件读取结构

python - 使用字典值时的字符串格式问题

c - 指向二维结构数组的指针

c - 在 C 中释放二维数组的内存时出现异常警告

c - 在 scanf() 之后,我如何 "delete"无用

c# - 为什么 .NET 在 String.Format 中使用与默认 Math.Round() 算法不一致的舍入算法?

java - 将秒转换为人类可读格式 MM :SS Java