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

C语言如何清空字符串 解决循环内字符串输入复用失效问题

问题分析与修复方案

核心问题与对应修正点如下:

  • 数组未初始化直接比较:choice数组定义后未赋值就调用strcmp判断,此时数组内是随机垃圾值,可能导致逻辑异常甚至程序崩溃。
  • memset使用错误且多余:你用strlen(choice)作为清空长度的逻辑完全没必要:scanf("%s")读取有效字符串时会自动在末尾追加\0结束符,旧内容只要不超过新字符串长度,完全不会影响strcmp判断;如果choice中不存在\0,strlen会越界访问内存,触发未定义行为。
  • 输出缓冲未刷新导致假死:所有业务提示的printf都没有加换行符,而标准输出默认是行缓冲模式,内容没遇到换行就不会主动刷新到屏幕上,你会误以为程序卡住没进入下一次循环,实际上程序已经在等待输入,只是提示信息还留在缓冲里没有显示。
  • scanf存在缓冲区溢出风险:%s没有限制读取长度,输入超过254个字符就会溢出数组,破坏内存数据。
修复后的代码
#include <stdio.h>
#include <string.h>

int main() {
    char choice[255];
    // 先执行一次输入逻辑再判断是否退出,避免未初始化数组比较问题
    do {
        printf("what would you like to do?\n");
        printf("1 - login\n");
        printf("2 - who\n");
        printf("3 - Lookup\n");
        printf("4 - logout\n");
        // 限制读取长度,预留1位存储\0避免溢出
        scanf("%254s", choice);

        if(strcmp(choice,"login")==0){
            /* send server ip and player id*/
            // 末尾加换行刷新输出缓冲
            printf("logging you in...\n");
        }
        else if(strcmp(choice,"who")==0) {
            /* send server ip and player id*/
            printf("fetching all available players...\n");
        }
        else if(strcmp(choice,"lookup")==0) {
            /* send server ip and player id*/
            printf("Who are you looking for?\n");
        }
    } while (strcmp(choice,"logout")!=0);
    return 0;
}
补充说明

如果确实有清空数组的需求,直接用memset(choice, 0, sizeof(choice))即可,不要用strlen计算清空长度。正常场景下不需要每次循环清空数组,scanf写入的新字符串的结束符会自动截断旧内容,不影响逻辑判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 22:45:06