[英]enforce sscanf input value to be unqiue in c
代码链接: https://godbolt.org/z/dxn38f53h
试图复制/理解这篇文章: https://stackoverflow.com/a/47587807/15603477 。
问题是团队可以复制。
试图找到一种方法来检查sscanf
输入值与所有先前输入相比是唯一的(忽略默认值 0)。
预期结果:当stdin
输入(团队编号)值重复时,使 function输入重置为“开始”:
printf("\nEnter your team: ");
而 x>=1 阻止那部分是我到目前为止所尝试的。
void input(int a[NROW][NCOL], int teams[NROW])
{
int x, y;
for (x = 0; x < NROW; x++) {
for (;;) {
int rtn;
printf("\nEnter your team: ");
rtn = scanf("%d", &teams[x]);
while (x >= 1) {
printf("x=\t%d\n", x);
for (int j = 1; j <= x; j++) {
if (teams[j] == teams[j - 1]) {
fprintf(stderr,"duplicate team number.\n");
// x = x + 1;
printf("x=%d\n", x);
break;
} else {
break;
}
}
break;
}
if (rtn == 1)
break;
else if (rtn == EOF) {
fprintf(stderr, "user canceled input.\n");
exit(EXIT_FAILURE);
}
fprintf(stderr,"error: invalid input.\n");
empty_stdin();
}
for (y = 0; y < NCOL; y++) {
for (;;) {
int rtn;
printf("Enter team[%d] score [%d]: ",teams[x],y+1);
rtn = scanf("%d", &a[x][y]);
if (rtn == 1)
break;
else if (rtn == EOF) {
fprintf(stderr, "user canceled input.\n");
exit(EXIT_FAILURE);
}
fprintf(stderr, "error: invalid input.\n");
empty_stdin();
}
}
}
}
尝试定位重复项的循环是不正确的:您比较teams[j]
和teams[j - 1]
而不是比较teams[j]
和teams[x]
并且j
的范围应该包括0
。
此外,即使scanf()
未能读取团队编号,您也会执行扫描。
您应该首先测试有效输入,然后检查重复项,如果没有找到重复项,则接受输入。
这是修改后的版本:
void input(int a[NROW][NCOL], int teams[NROW])
{
int x, y;
for (x = 0; x < NROW; x++) {
for (;;) {
int rtn, j;
printf("\nEnter your team: ");
rtn = scanf("%d", &teams[x]);
if (rtn != 1) {
if (rtn == EOF) {
fprintf(stderr, "user canceled input.\n");
exit(EXIT_FAILURE);
}
fprintf(stderr,"error: invalid input.\n");
empty_stdin();
continue;
}
for (j = 0; j < x; j++) {
if (teams[j] == teams[x])
break;
}
if (j < x) {
fprintf(stderr, "duplicate team number.\n");
continue;
}
break;
}
for (y = 0; y < NCOL; y++) {
for (;;) {
int rtn;
printf("Enter team[%d] score [%d]: ", teams[x], y+1);
rtn = scanf("%d", &a[x][y]);
if (rtn == 1)
break;
if (rtn == EOF) {
fprintf(stderr, "user canceled input.\n");
exit(EXIT_FAILURE);
}
fprintf(stderr, "error: invalid input.\n");
empty_stdin();
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.