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

C语言中sscanf读取多负整数异常:仅识别-23未识别-4、-3

C语言提取正负整数时无法识别部分负号的问题

编写了一段C语言代码,意图从包含整数与字符的输入中提取正负整数存入数组,最终将每组整数逆序输出,但输入中的–4和–3未被正确识别为负数,仅读取到-23,以下是代码、输入输出及问题排查:

代码实现

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

#define M 1000

int main(void)
{
    char a;
    char enteros[M];
    int output[M];
    int newline = 0;
    int count = 0;
    int x = 0;
    int index = 0;
    int num = 0;
    char *str;

    while (fscanf(stdin, "%c", &a) != EOF)
    {
        enteros[count] = a;
        count++;
    }

    enteros[count] = '\0';

    str = enteros;

    while (*str)
    {
        x = 1;
        if (sscanf(str, "%d%n", &num, &x) == 1)
        {
            output[index] = num;
            newline = 0;
            index++;
        }

        str += x;

        for (; *str; str++)
        {
            if (*str >= '0' && *str <= '9') /* positive value */
                break;
            if (*str == '-' && *(str + 1) >= '0' && *(str + 1) <= '9') /* negative */
                break;
            else if (!newline && isalpha((unsigned int)*str))
            {
                while (index != 0)
                {
                    printf(" %d", output[index - 1]);
                    index--;
                }
                printf("\n");
                newline = 1;
            }
        }
    }

    return 0;
}

输入内容

1 8 4000 2 -23 end 51 87 end –4
–3 2 end

实际输出

-23 2 4000 8 1
 87 51
 2 3 4

问题排查与解决

核心问题是输入中的–4和–3使用了全角破折号(–),而非代码中判断的半角减号(-):

  1. 代码中判断负号的条件仅针对半角减号*str == '-',无法识别全角破折号;
  2. 全角破折号会被代码当成普通非数字字符处理,导致后面的4和3被单独识别为正整数,而非负数的一部分;
  3. 即使跳过循环判断,sscanf的%d格式符也不支持解析全角破折号开头的数字。

解决方法

  • 修正输入:将所有全角破折号替换为半角减号;
  • 修改代码:在负号判断条件中增加对全角破折号的支持,修改为:
    if ((*str == '-' || *str == '–') && *(str + 1) >= '0' && *(str + 1) <= '9') /* 支持半角/全角负号 */
        break;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:50:38