c - 使用 fscanf 读取空格

标签 c file scanf

我想从一个存储这样数据的文件中读取:

Max Mustermann 12345

现在我想用这段代码读取数据:

FILE *datei;
char text[100];
int il;

datei = fopen ("datei.txt", "r");

if (datei != NULL)
{
    fscanf(datei, ": %s %d", text, &il);

    printf("%s %d", text, il);
    fclose(datei);
}

但这段代码只扫描“Max”(因为有一个空格),然后扫描下一个“Mustermann”作为 int。我想知道 'Max Mustermann' 是 char 数组和 int 变量中的 '12345'。如何使用 fscanf 读取空格?或者是否有其他方法可以从文件中获取不同变量的值?

最佳答案

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

int main(int argc, char *argv[]) {
    FILE *datei;
    char text[100];
    char line[128], *p;
    int il;

    datei = fopen ("data.txt", "r");

    if (datei != NULL){
        if (fgets(line, sizeof(line), datei) != 0){ //read one line
            p=strrchr(line, ' ');//search last space
            *p = '\0';//split at last space
            strcpy(text, line);
            il = atoi(p+1);//or sscanf(p+1, "%d", &il);
            printf("%s, %d", text, il);
        }
        fclose(datei);
    }
    return 0;
}

也使用 fscanf。

char *p;
//"%[^0123456789] is reading other digit character
fscanf(datei, "%[^0123456789]%d", text, &il);
p=strrchr(text, ' ');//search last space
*p = '\0';//replace last space (meant drop)
printf("%s, %d", text, il);

手工制作?

#include <ctype.h>
    if (datei != NULL){
        int ch, i=0;
        while(EOF!=(ch=fgetc(datei)) && i<100-1){
            if(isdigit(ch)){
                ungetc(ch, datei);
                text[--i] = '\0';
                break;
            }
            text[i++] = ch;
        }
        if(i >= 99){
            fprintf(stderr, "It does not conform to the format\n");//maybe no
            fclose(datei);
            return -1;
        }
        fscanf(datei, "%d", &il);
        printf("%s, %d\n", text, il);
        fclose(datei);
    }

关于c - 使用 fscanf 读取空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17067830/

相关文章:

c - 以特定格式读取日期和时间

c - 如何从 IRP_MJ_CREATE 回调中获取 OpenResult?

c - 字符串复制中的段错误

c - Windows 复制命令如 XCOPY、COPY、ROBOCOPY 在 System() 中的 C 语言中不起作用

c - 打开文件进行编辑

c - 默认情况下,读取输入缓冲区中的哪个字符会使 scanf() 停止读取字符串?

编译器检查以确保我在裸机而不是托管环境中运行

c - redisAsyncConnect() 与 redisConnect() 有何不同?

excel - 如何改进 Excel 数据连接的刷新?

c - 如何在c中将字符串存储在数组中