Problem Description: Enter a word from the keyboard until you press ENTER, the characters are output as is, but only one space is output if there is more than one space in a row.
For example, input: I am a teacher., output I am a teacher.
Author's code:
1#include"stdafx.h"2 3 intMain ()4 {5 CharC' /'), M (' /');6 7 Do8 {9c =GetChar ();Ten if(M = =' ') && (c = =' ')) One { APutchar ('\b'); - } - Putchar (c); them =C; - -} while(c! ='\ n'); - + return 0; -}
The Teacher's code:
1#include <stdio.h>2 intMain ()3 { 4 CharC, frontisspace=0;//Frontisspace used to memorize whether the preceding symbol is a space, a space, a value of 1, not a space, 05 while((C=getchar ())! ='\ n') 6 { 7 if(c!=' ') 8 { 9Frontisspace=0;//after reading the next character, the current character is the next so-called previous, its value is not a space, so the assignment is 0Ten Putchar (c); One } A Else if(frontisspace==0)//If the previous is not a space, the current space is to be output - { -Putchar (c);//the output is a space theFrontisspace=1;//after reading the next character, you need to know that the current character, that is, the next so-called previous, its value is a space, so the assignment is 1 - } - } - return 0; +}
Feelings:
It is difficult to think of this problem for the first time. This time can write "pseudo-code" or draw a flowchart, not too much trouble, in fact, can greatly improve efficiency . For example, before writing the code, you can write a pseudo-code:
Input character "Use intermediate variables to determine if the previous character is space"
1. Yes: output backspace
2. No: output character (data processing)
"Store character in intermediate variable" returns a loop
=
"C Language and Programming" Project 1-36-3: Eliminate extraneous spaces