c - 由于 printf() 和 scanf() 导致的意外输出
问题描述
我实现了一个 C 程序,您可以在其中输入一系列用空格分隔的数字,例如1 2 3 4 5
. 程序看到进入每个序列的最大时间限制是 15 秒。
代码导致输出:
Kindly specify the length of the sequence: 3
Kindly specify the number of the colors in the sequence: 3
Input sequence:
Sorry, I got tired waiting for your input. Good bye!
Input sequence:
代替
Kindly specify the length of the sequence: 3
Kindly specify the number of the colors in the sequence: 3
Input sequence:
我的意思是它不允许我在输出的第 3 行输入序列,而是继续并完成一个计时器循环,然后让我输入序列。这是为什么?如果我删除以下代码中的and函数,则不会发生这种情况。printf
scanf
main()
这是我的代码:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define INPUT_LEN 10
/* read a guess sequence from stdin and store the values in arr */
void readString(int *arr)
{
fflush(stdout);
time_t end = time(0) + 15; //15 seconds time limit.
int flags = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK);
char answer[INPUT_LEN];
int pos = 0;
while (time(0) < end)
{
int c = getchar();
/* 10 is new line */
if (c != EOF && c != 10 && pos < INPUT_LEN - 1)
{
answer[pos++] = c;
}
/* if new line entered we are ready */
if (c == 10)
break;
}
answer[pos] = '\0';
if (pos > 0)
{
int x = 0;
char *ptr = strtok(answer, " ");
while (ptr != NULL)
{
sscanf(ptr, "%d", (arr + x++));
ptr = strtok(NULL, " ");
}
}
else
{
puts("\nSorry, I got tired waiting for your input. Good bye!");
// exit(EXIT_FAILURE);
}
}
int main()
{
int seqlen = 0, colors = 0;
printf("Kindly specify the length of the sequence: ");
scanf("%d", &seqlen);
printf("Kindly specify the number of the colors in the sequence: ");
scanf("%d", &colors);
int *guessSeq = (int *)malloc(sizeof(int) * 5);
int found = 0, attempts = 0;
while (!found)
{
if (++attempts > 10)
break;
/* IMPLEMENT the main game logic here */
printf("Input sequence: ");
readString(guessSeq);
}
return (0);
}
解决方案
推荐阅读
- vaadin - Vaadin 11 - 如何在 application.yml 中设置 productionMode
- regex - Python 2.7 正则表达式与所需模式不匹配
- spring - 在类路径中找不到属性文件 - 部署 EAR 时出错
- javascript - 分支 IO 和反应网络应用程序:'分支'未定义
- ios - 向 iOS 用户显示企业应用程序正在安装
- java - FragmentPagerAdapter Fragment getItem 位置错误?
- c++ - QGraphicsWidget中的FramelessWindowHint?
- azure - Azure AD B2C Microsoft 帐户 redirect_uri 失败
- regex - 至少包含 x 个字符和 x 个数字的正则表达式匹配字符串
- android - Android从网站中提取多个表