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

在C语言中扫描逗号分隔字符串时如何省略逗号后的空格

处理逗号分隔字符串时移除第二个字段开头空格的问题

我用C语言读取逗号分隔的字符串时遇到一个问题:第二个字符串输出开头会自带空格。比如输入hello world, o wor时,现有代码输出的第二个字段前带空格,我需要输出开头无空格的结果,同时第一个字段输出后要带一个空格。

现有代码

#include <stdio.h>
int main()
{
    char s[30];
    char r[30];
  
    scanf("%[^,],%[^\n]",s,r);
    
    printf("%s\n",s);
    printf("%s",r);

    return 0;
}

当前输入输出情况

输入:

hello world, o wor

当前输出:

hello world
 o wor

期望输出:

hello world 
o wor

解决方法

问题根源在scanf的格式控制串上:原格式%[^,],%[^\n]里,逗号后面没有处理空白字符,导致输入中逗号后的空格被直接读取到第二个字符串中。另外要调整第一个输出的格式来匹配需求,具体修改如下:

  1. 在scanf的逗号后添加一个空格,让scanf自动跳过逗号后的任意空白字符(包括空格、制表符等)
  2. 修改第一个printf的格式,在%s后添加一个空格,满足期望的输出格式

修改后的代码:

#include <stdio.h>
int main()
{
    char s[30];
    char r[30];
  
    scanf("%[^,], %[^\n]", s, r);
    
    printf("%s \n", s);
    printf("%s", r);

    return 0;
}

测试结果

输入hello world, o wor时,输出将符合期望:

hello world 
o wor

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 11:10:12