gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:43:34 25 4
gpt4 key购买 nike

我对 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 吗?

最佳答案

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

#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;
}

关于c - 退出 scanf 使用较少的参数然后指定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26691470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com