首页 > 解决方案 > 由于 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函数,则不会发生这种情况。printfscanfmain()

这是我的代码:

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

标签: ctimer

解决方案


推荐阅读