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

printf无法输出完整语句,C语言作业输出异常求助

问题根源

你的问题出在输入读取环节:scanf("%s", &sentence); 中,%s 格式符会在遇到空格、制表符、换行符这类空白字符时停止读取。也就是说,你输入的句子只要包含空格,sentence 数组里只会存储第一个空格前的内容,后面的部分根本没被读进来,自然输出不完整。

修复方案

用 fgets() 代替 scanf() 来读取整行输入,它能读取包含空格的完整句子,直到遇到换行符或达到数组上限。注意 fgets() 会把输入末尾的换行符也读进数组,需要手动去掉:

#include <stdio.h>
#include <ctype.h>
#include <string.h> // 需要用到strlen()和strchr()

int main(int argc, char *argv[]) {
    char sentence[200];
    int i;

    printf("Enter a sentence:");
    // 用fgets读取整行,第二个参数是数组大小,第三个参数是输入流
    fgets(sentence, sizeof(sentence), stdin);
    
    // 去掉fgets读入的换行符(如果存在)
    char *newline = strchr(sentence, '\n');
    if (newline != NULL) {
        *newline = '\0';
    }

    // 以下是你原来的格式处理逻辑,保留即可
    for(i = 0; sentence[i]; i++)
    {
        if(isspace(sentence[i]))
            sentence[i] = ' ';
    }

    i = 0;
    while(sentence[i] != '\0')
    {
        if(sentence[i] == ' ' && sentence[i+1] == ' ')
            for(int j = i; sentence[j]; j++)
            {
                sentence[j] = sentence[j+1];
            }
        else
            i++;
    }

    sentence[0] = toupper(sentence[0]);
    for(i = 1; sentence[i]; i++)
    {
        sentence[i] = tolower(sentence[i]);
    }

    printf("%s\n", sentence);

    return 0;
}
额外说明
  • fgets() 是读取整行输入的标准方法,适合处理包含空格的文本;
  • 必须检查并去掉换行符,否则你的格式处理逻辑会把换行符转换成空格,影响最终输出;
  • 你的格式处理逻辑本身没有问题,注释后仍异常就是因为输入根本没读全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 06:00:18