編寫一個將輸入復制到輸出的程序,並將其中連續的多個空格用一個空格代替。


  當前輸入字符可以分為兩種情況:

  1、當前輸入字符不為空,則直接輸出這個字符即可;

  2、當前輸入字符為空,這種情況又可以分為兩種情況:

  ①、上一個輸入字符也為空,則忽略此次輸入的空格即可;

  ②、上一個輸入字符不為空,則直接輸出這個字符即可。

 基本思想是:
  設置兩個變量,分別記錄當前輸入的字符和上一次輸入的字符,“上一個字符”初始化為EOF。
  如果當前輸入字符為空,上一個輸入字符也為空,則忽略當前輸入的字符。

View Code
#include <stdio.h>


main()
{
    int c, pc;    /* c = character, pr = previous character */

    /* set pc to a value that wouldn't match any character, in case
    this program is over modified to get rid of multiples of other
    characters */
    pc = EOF;

    while ((c = getchar()) != EOF)
    {
        if (c == ' ')
            if (pc != c)    /* or if (pc != ' ') */
                putchar(c);
        /* We haven't met 'else' yet, so we have to be a little clumey */
        if (c != ' ')
            putchar(c);
        pc = c;
    }
}
View Code
#include <stdio.h>

main()
{
    int c;    /* 用於存放當前輸入的字符 */
    int pc;    /* 用於存放當前輸入的上一個字符 */
    
    while((c = getchar()) != EOF)
    {
        if (c != ' ')
        {
            putchar(c);
        }
        else if (pc != ' ')
        {
            putchar(c);
        }

        pc = c;
    }

}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM