C语言 printf()不显示完整句子

cld4siwp  于 2023-10-16  发布在  其他
关注(0)|答案(1)|浏览(120)

我在做学校作业,却被结果卡住了。

#include <stdio.h>
#include <ctype.h>

int main(int argc, char *argv[]) {
    /* Declare input variable */
    char sentence[200];     // array that large enough for an sentence
    int i;

    /* Print the prompt */
    printf("Enter a sentence:");
    scanf("%s", &sentence);

    /* Change all white space characters to a space */
    for(i = 0; sentence[i]; i++)
    {
        if(isspace(sentence[i]))    //isspace to convert space, \t, \n
            sentence[i] = ' ';
    }

    /* Remove multiple spaces */
    i = 0;

    while(sentence[i] != '\0')      // \0 = NULL byte -> 0x30, address
    {
        if(sentence[i] == ' ' && sentence[i+1] == ' ')      // if there is two space
        for(int j = i; sentence[j]; j++)
        {
            sentence[j] = sentence[j+1];                    // eliminate one space
        }
        else
          i++;
    }

    sentence[0] = toupper(sentence[0]);     // Capitilize the first character of the sentence
    for(i = 1; sentence[i]; i++)
    {
        sentence[i] = tolower(sentence[i]);
    }

    /* Display the Output */
    printf("%s\n", sentence);

    return 0;
}

我按照指示做了,但结果是这样:enter image description here
我试着在注解了中间部分后构建并运行代码,看看输入是否与输出相同。但结果和照片上的一样。我不认为这是中间部分的问题,但我不知道问题是什么。

wwtsj6pe

wwtsj6pe1#

这里不需要“&”:

scanf("%s", &sentence);

事实上,你不能在scanf函数的帮助下得到整个句子。你需要像fgets这样的函数。举例来说:

fgets(sentence, sizeof sentence, stdin);

你的问题就解决了
示例输出:

Enter a sentence:this sentence has  a double  space 
This sentence has a double space

相关问题