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

C语言中使用while循环读取字符序列的技术问题求助

问题分析与解决方案

原代码的问题

  1. scanf("%c", &cinput)仅读取输入的第一个字符(比如输入1 2 3时只拿到'1'),后续的空格、2、3都没被读入。
  2. input = &cinput让指针指向单个char变量,strlen(input)会因为找不到字符串结束符'\0'而非法访问内存,结果完全不可靠。

解决方案

方案1:逐个读取并处理字符(无需存储)

如果不需要保存整个输入序列,只是要逐个处理每个字符(包括空格),可以用while循环配合getchar()实现,直到用户按下回车:

#include <stdio.h>

int main() {
    char c;
    printf("type numbers:\n");
    
    // 循环读取每个字符,直到遇到换行符
    while ((c = getchar()) != '\n') {
        // 这里可根据需求处理字符,比如打印、判断是否为数字等
        printf("读取到字符: %c\n", c);
        // 示例:提取数字字符
        if (c >= '0' && c <= '9') {
            printf("这是数字: %c\n", c);
        }
    }
    
    return 0;
}

方案2:动态存储整个输入序列(需后续访问)

如果需要保存整个输入序列以便后续访问任意位置的字符(比如你要获取input[2]的值),可以用动态内存分配来实现,无需提前知道输入长度:

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

int main() {
    char *input = NULL;
    char c;
    int length = 0;
    int capacity = 0;
    
    printf("type numbers:\n");
    
    // 逐个读取字符直到换行
    while ((c = getchar()) != '\n') {
        // 内存容量不足时扩容,初始分配4字节,每次翻倍
        if (length >= capacity) {
            capacity = (capacity == 0) ? 4 : capacity * 2;
            char *temp = realloc(input, capacity * sizeof(char));
            if (temp == NULL) {
                perror("内存分配失败");
                free(input);
                return 1;
            }
            input = temp;
        }
        input[length++] = c;
    }
    
    // 为字符串添加结束符
    if (length > 0) {
        char *temp = realloc(input, (length + 1) * sizeof(char));
        if (temp == NULL) {
            perror("内存分配失败");
            free(input);
            return 1;
        }
        input = temp;
        input[length] = '\0';
    }
    
    // 验证结果
    if (input != NULL) {
        printf("完整输入: %s\n", input);
        // 输入1 2 3时,input[2]就是'2'
        if (length >= 3) {
            printf("input[2]的值: %c\n", input[2]);
        }
        free(input); // 记得释放动态分配的内存
    }
    
    return 0;
}

说明

  • 方案1适合边读边处理的场景,内存开销极小;
  • 方案2适合需要保存输入内容后续操作的场景,通过动态扩容适配任意长度输入。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 00:50:12