您如何在C中向用户问多个问题?

时间:2018-11-25 23:04:54

标签: c

我是“ C编程”的新手,我已经用Google搜索了我的答案,但是我似乎无法获得想要的东西。我正在制作一个简单的2问题程序。下面列出了代码:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char characterName[] = "Mike";
    int age = 0;

    printf("Enter your age, %s.\n", characterName);
    scanf("%d", &age);
    printf("Your being %d is old older than me and my brother "
           "which was the first computer.Hahaaa.... \n", age);

    return 0;
}

这是下一个问题:

char str[50];
{
    printf("Anything to say about my comment? \n");
    scanf ("%[^\n]", str);
    printf("That was a good answer. I wasn't expecting that from you.\n");
    return 0;
}

1 个答案:

答案 0 :(得分:2)

问问题并返回响应的函数如何?

#include <stdio.h>

/*
 * Prompt the user with the given question, return their
 * input in answer, up to max_answer_length bytes 
 * returns 1 for ok, 0 on error.
 */
int askQuestion(const char *question, char *answer, const size_t max_answer_length)
{
    int input_ok = 1;  

    // Show the user the question
    printf( "%s: ", question );

    // Throw away any existing input in the user's input-queue
    // (like if they answered with a really-long string previously)
    fflush(stdin);

    // Read a line of input from the user into <answer>, but not more
    // than <max_answer_length>-1 bytes are accepted (see fgets() for details)
    // If the fgets() returns EOF or an error, make sure we remember it
    if ( fgets( answer, max_answer_length, stdin ) == NULL )
        input_ok = 0;

    // return whether there was an error on input
    return input_ok;
}

int main(void)
{
    char answer_buffer[200];

    askQuestion( "What is your favourite fruit?", answer_buffer, sizeof(answer_buffer) );
    printf( ">> %s\n", answer_buffer );

    askQuestion( "How long have you been programming C?", answer_buffer, sizeof(answer_buffer) );
    printf( ">> %s\n", answer_buffer );

    return 0;
}