然后指定使用较少参数退出scanf

时间:2014-11-01 18:13:53

标签: c scanf

我的scanf有问题。我写了一个小计算器程序,但现在我想在输入单个0时退出计算器。

 int main(void) {
     int first;
     char operation;
     int second;
     while(1) {
        int correct = scanf("%d %c %d", &first, &operation, &second);
        if(first == 0 && correct == 1) return(0);
     }
 return 0;
 }

我的代码无效,因为scanf会等到输入3件事。当只输入一个0时,我可以退出scanf吗?

1 个答案:

答案 0 :(得分:1)

读取用户输入行,然后进行扫描。

#include <limits.h>
// First determine a buffer large enough for reasonable worst case input
// S_SIZE_INT is big enough for INT_MIN
#define S_SIZE_INT (sizeof int * CHAR_BIT/3 + 3)
#define S_SIZE_INT_CHAR_INT (S_SIZE_INT*2 + 1 + 3 /*sep*/ +2 /*eol*/ +10 /*CYA*/)

int main(void) {

  int first;
  char operation;
  int second;

   while (1) {
     char buf[S_SIZE_INT_CHAR_INT];           
     if (fgets(buf, sizeof buf, stdin) == NULL) {
       break; // EOF detected
     } 
     int correct = sscanf(buf, "%d %c %d", &first, &operation, &second);

     // Best to test `correct` before testing `first` to know something was read
     // As commented by @mafso
     if (correct == 1 && first == 0) return(0);

   }
 return 0;
 }