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

C语言多行多变量输入失败,scanf_s使用问题技术求助

问题分析与修复方案

核心问题

  1. scanf_s格式字符串错误:你写的"%34s[^\n]"是错误语法,%s会在空白处截断输入,而%[^\n]才是读取整行(支持含空格的内容),二者不能混用。
  2. scanf_s参数传递错误:你用逗号把两个输入的参数连在一起,属于语法错误,正确做法是拆分两次独立的scanf_s调用。
  3. 缓冲区残留问题:第一次输入后的换行符会留在缓冲区,导致后续输入直接被跳过,且fflush(stdin)是标准C未定义行为,不能依赖。

修复后的代码

void filterByStationAndSensorType(TelemetryData* telemetryArray, int arraySize) {
    char stationType[34];
    char sensorType[20];
    int c; // 用于清空输入缓冲区

    printf("Enter the Station to filter (can include spaces): ");
#if (_MSC_VER > 1600)
    // 读取含空格的站点名称,直到换行符
    scanf_s("%[^\n]", stationType, (unsigned)sizeof(stationType));
    // 清空缓冲区残留的换行符
    while ((c = getchar()) != '\n' && c != EOF);

    printf("Enter the Sensor Type to filter: ");
    scanf_s("%19s", sensorType, (unsigned)sizeof(sensorType));
#else
    scanf("%[^\n]", stationType);
    while ((c = getchar()) != '\n' && c != EOF);
    scanf("%19s", sensorType);
#endif

    printf("Telemetry Data for Station '%s':\n", stationType);
    for (int i = 0; i < arraySize; ++i) {
        if (strstr(telemetryArray[i].location, stationType) != NULL) {
            if (strcmp(telemetryArray[i].sensorType, sensorType) == 0) {
                printf("SensorID: %s, SensorType: %s, Location: %s, Measurement: %.2f, "
                    "Status: %s\n",
                    telemetryArray[i].sensorID, telemetryArray[i].sensorType,
                    telemetryArray[i].location, telemetryArray[i].measurement,
                    telemetryArray[i].status);
            }
        }
    }
    printf("\n\n\nArraySize: %i\n\n", arraySize);
}

关键修复说明

  • 支持含空格的输入:使用%[^\n]格式说明符,可读取包含空格的站点名称(如"West Lake Station"),直到用户按下回车。
  • 安全清空缓冲区:用while ((c = getchar()) != '\n' && c != EOF);循环读取缓冲区残留字符,替代未定义的fflush(stdin),这是标准C中通用的缓冲区清理方法。
  • scanf_s正确调用:拆分两次独立的输入调用,每个格式字符串对应正确的参数,sizeof(数组名)直接传递总字节数即可,无需额外计算元素个数。

额外提示

  • 站点名称数组长度为34,最多支持33个字符的输入(留1位存字符串终止符),可添加输入长度提示避免截断;传感器类型用%19s匹配20位数组,同样避免缓冲区溢出。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 00:03:27