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

C语言单词查找程序输出出现多余换行的问题求助

问题:单词查找程序输出出现多余换行

我开发了一个单词查找程序,预期输出格式为"A palavra % está no texto!"或"A palavra % não está no texto!",但实际输出却分成了两行,示例如下:

A palavra NOITE
não está no texto!

我的代码如下:

#include <stdio.h>
#include <stdlib.h>
#define MAX 300
#define CHAR 20


int main(){
    int W, w; 
    scanf("%d ", &W); /*W is the number of words/lines in the matrix words*/
    char words[MAX][CHAR];

    for(w=0; w<W; w++){
        int c=0;
        do{
            scanf("%c", &words[w][c]);
            c++;
        }while(words[w][c-1]!= '\n' && c<CHAR);
    }
    
    /* the variable ultimate is declared in the complete code.In this example 
    the most important thing is the extra line-break in the output of the conditional if*/
    int ultimate=1, c=0;
    /*the variable l(line) is the line index of the word matrix. The c variable is the column index
    Supose that we have three words: words[0]=[NIGHT...000], words[1]=[SUN...000] and 
    words[2]=[MOON...000]*/
    int l=2;
    if(ultimate!=0){
        c=0;
        printf("A palavra ");
        do{
            printf("%c", words[l][c]);
            c++;
        }while(words[l][c-1]!='\0');
        printf(" está no texto!\n");
    }else{
        c=0;
        printf("A palavra ");
        do{
            printf("%c", words[l][c]);
            c++;
        }while(words[l][c-1]!='\0');
        printf(" não está no texto!\n");
    }                                
    return 0;
}

我尝试将整句输出在同一行但未能成功。由于需要用字符矩阵存储单词,我使用do-while循环打印当前分析行的所有字符,矩阵的每一行存储一个单词,这部分功能正常,但printf输出时出现了多余换行,请问该如何解决?


解决方案

问题核心是读取单词时把换行符'\n'也存入了数组,导致打印时输出这个换行符拆分整句;同时代码未手动添加字符串终止符'\0',存在潜在越界风险。

修改步骤:

  1. 读取单词时跳过换行符,不将其存入数组
  2. 在每个单词末尾手动添加'\0',确保字符串正确终止

优化后的读取代码(保留原循环结构):

for(w=0; w<W; w++){
    int c=0;
    do{
        scanf("%c", &words[w][c]);
        // 遇到换行符则停止,不存入数组
        if(words[w][c] == '\n'){
            break;
        }
        c++;
    }while(c < CHAR-1); // 预留一个位置给终止符
    // 添加字符串终止符
    words[w][c] = '\0';
}

更简洁的读取方式(使用getchar处理):

for(w=0; w<W; w++){
    int c=0;
    // 跳过前置的换行符(比如输入W后的残留换行)
    while((words[w][c] = getchar()) == '\n');
    c++;
    // 读取单词字符,直到换行或达到字符上限
    while(c < CHAR-1 && (words[w][c] = getchar()) != '\n'){
        c++;
    }
    // 添加终止符
    words[w][c] = '\0';
}

修改后,words数组中的单词不再包含换行符,打印时就能保持整句在同一行输出。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 19:52:27