You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中sscanf无法读取目标三个变量的问题排查

问题:C语言sscanf读取带空格的字符串出错,结果不符合预期

问题描述

我有一个内容为323,John of Sea,11.2的文件,希望通过逗号分割将内容读取到int类型变量number1、char数组Name[100]、float类型变量number2中。编写了如下C程序:

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

int main()
{
    int number1;
    float number2;
    char Name[100],Phrase[100];
    FILE *inf ;
    
    if((inf = fopen("Information.txt","r")) == NULL){
        perror("Information.txt");
        return EXIT_FAILURE;
    }
    
    while (fgets(Phrase,100,inf) != NULL )
    {   
        sscanf(Phrase , "%d,%s,%f", &number1 , Name, &number2 ); 
        printf("%d  %s  %f \n", number1, Name, number2);   
    }
    
}

运行结果为323 John 0.000000,但预期结果是323 John of Sea 11.2。

补充的最小复现代码:

#include <stdio.h>

int main()
{
    int number1;
    float number2;
    char Name[100];

    sscanf("323,John of Sea,11.2\n", "%d,%s,%f", &number1, Name, &number2);
    printf("%d  %s  %f \n", number1, Name, number2);
}

错误原因

问题出在sscanf的格式控制符%s上:

  • %s在C语言中会读取到第一个空白字符(空格、换行、制表符等)就停止,所以它只会把John读入Name数组,剩下的 of Sea留在输入缓冲区里。
  • 后续的%f尝试从 of Sea这个位置读取浮点数,读取失败后,number2的值会保持未初始化的随机状态(这里显示为0.000000属于未定义行为)。

解决方案

要读取包含空格但以逗号结尾的字符串,需要使用sscanf的**扫描集(scan set)**语法,指定读取除了逗号之外的所有字符:

修改格式控制字符串为"%d,%[^,],%f",其中:

  • %[^,]表示读取所有不是逗号的字符,直到遇到逗号为止,这样就能完整读取John of Sea这个带空格的字符串。

修改后的最小复现代码

#include <stdio.h>

int main()
{
    int number1;
    float number2;
    char Name[100];

    sscanf("323,John of Sea,11.2\n", "%d,%[^,],%f", &number1, Name, &number2);
    printf("%d  %s  %f \n", number1, Name, number2);
}

修改后的文件读取程序

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

int main()
{
    int number1;
    float number2;
    char Name[100],Phrase[100];
    FILE *inf ;
    
    if((inf = fopen("Information.txt","r")) == NULL){
        perror("Information.txt");
        return EXIT_FAILURE;
    }
    
    while (fgets(Phrase,100,inf) != NULL )
    {   
        sscanf(Phrase , "%d,%[^,],%f", &number1 , Name, &number2 ); 
        printf("%d  %s  %f \n", number1, Name, number2);   
    }
    
}

注意事项

  • 确保Name数组的大小足够容纳目标字符串,避免缓冲区溢出。
  • 如果字符串前后可能有多余的空格,可以在扫描集前或后添加空格,比如"%d, %[^,], %f"来忽略逗号前后的空格。

内容的提问来源于stack exchange,提问作者jvq3xd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 12:21:00