"C Language and Programming" Project 1-36-3: Eliminate extraneous spaces

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.