C语言 编程练习 if else语句

使用if else语句编写一个程序读取输入,读到#停止。使用感叹号替换句号,用两个感叹号替换原来的感叹号,最后报告进行了多少次替换。

#include<stdio.h>
#include<ctype.h>
int main()
{
    char ch;
    int a = 0,b = 0;
    while((ch = getchar()) != '#')
    {
        if(ch == '.')
        {
            a++;
            putchar(ch - 13);
        }
        if(ch == '!')
        {
            b++;
            putchar(ch);
            putchar(ch);
        }
        if(isalpha(ch))
            putchar(ch);
    }
    printf("\n句号替换了%d次\n",a);
    printf("感叹号替换了%d次\n",b);
    
    return 0;
}

#include <stdio.h>

int main() 
{
    char ch;
    int count = 0;
    while ((ch = getchar()) != '#')
    {
        if (ch == '.') 
        {
            putchar('!');
            count++;
        } 
        else if (ch == '!')
        {
            putchar('!');
            putchar('!');
            count++;
        }
        else 
       {
            putchar(ch);
        }
    }

    printf("\n%d次", count);

    return 0;
}

【以下回答由 GPT 生成】

当然可以帮你完成这个程序!下面是我的解决方案:

#include <stdio.h>

int main() {
    char input;
    int count = 0;

    printf("请输入一段文字,使用'#'作为结束符:\n");

    while (1) {
        scanf("%c", &input);

        if (input == '#') {
            break;
        }

        if (input == '.') {
            putchar('!');
            count++;

            if (input == '.') {
                putchar('!');
                count++;
            }

        } else {
            putchar(input);
        }
    }

    printf("\n替换的次数:%d\n", count);

    return 0;
}

我先声明了一个字符变量 input 和一个整数变量 count,分别用来存储读取的输入字符和替换次数。

然后,在进入循环之前,我输出了一段提示文字,让用户输入一段文字,并使用 # 作为结束符。

接下来,我使用一个无限循环 while(1) 来读取输入的字符。每次循环开始时,我使用 scanf("%c", &input) 从输入流中读取一个字符,并存储在变量 input 中。

然后,我使用 if 语句来进行不同的处理逻辑。

如果读取到的字符是 #,就使用 break 语句跳出循环。

如果读取到的字符是 .,则将字符 ! 输出到屏幕,并将替换次数 count 加一。然后,我再次检查输入的字符是否是 .,如果是的话,再次输出字符 !,并将替换次数 count 再加一。这样,就实现了将句号替换为两个感叹号的功能。

如果读取到的字符不是 #.,则直接将该字符输出到屏幕。

最后,在循环结束后,我使用 printf 输出替换的次数 count

这样,你就可以使用这个程序来读取输入,替换句号,并报告替换的次数了。希望对你有帮助!如果还有其他问题,请随时向我提问。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^