C primer plus (第六版)第七章 编程练习第4题,第5题
题目:
4.使用if else语句编写一个程序读取输入,读到#停止。用感叹号替换句号,用两个感叹号替换原来的感叹号,最后报告进行了多少次替换。
#include <stdio.h>
int main()
{char ch;int num1 = 0;int num2 = 0;printf("Please entry a sentences:\n");while ((ch = getchar()) != '#'){if (ch == '.') //情况1,当ch为.打印!{putchar('!');num1++; //.替换数统计}else if (ch == '!') //情况2,当ch为!打印!!{printf("!!");num2++; //!替换数统计}else //情况3,其他的不变putchar(ch);}printf("total \'.\' replace %d times.\n",num1);printf("total \'!\' replace %d times.\n",num2);return 0;
}
5.使用switch重写练习4。
#include <stdio.h>
int main()
{char ch;int num1 = 0;int num2 = 0;printf("Please entry a sentences:\n");while ((ch = getchar()) != '#'){switch (ch){case '.':putchar('!');num1++;break;case '!':printf("!!");num2++;break;default:putchar(ch);break;}}printf("total \'.\' replace %d times.\n",num1);printf("total \'!\' replace %d times.\n",num2);return 0;}