1. 程式人生 > >C語言輸入函式作為迴圈條件的幾種用法

C語言輸入函式作為迴圈條件的幾種用法

C語言有  scanf()、gets()、getchar()、getc()、fscanf()、fgets()等函式 接受使用者的輸入。可以利用它們的返回值做迴圈的條件表示式。

1.scanf() 如果成功 返回引數的個數

    int value;

    float cast;

    while(scnaf("%d%f") == 2)

    {.................................}

2. gets() 函式返回接受字串的地址

    #define SIZE 20

    char str[SIZE];

      while(gets(str) != NULL && str[0] != '\0';

  {

   ........................................................

  }

3.getchar() 這個更簡單 可以定義結束的字元。

  char ch;

  while((ch = getchar()) != '\n')

  { 

  ................................................

  }

getc() 和 fscanf()、fgets() 可以對應相應的用法。

補充:

按行輸入 防止 gets()接受到空行

while(getchar() != '\n')

 continu;
while(gets(pstr) !=NULL&&pstr[0] !='\0')
{
..........................................................
}
while(fgets(stdin,pstr) !=NULL&&pstr[0] !='\n')
{
..........................................................
}