почему вторая итерация for-l oop не ожидает ввода пользователя - PullRequest
0 голосов
/ 10 февраля 2020

У меня проблема с для l oop. Когда я go через вторую итерацию, программа не ждет ввода пользователя. Любая помощь с благодарностью принята.

#include <stdio.h>
#include "dogInfo.h"


main()
{
    struct dogInfo dog[3];  //Array of three structure variable
    int ctr;

    //Get information about dog from the user
    printf("You will be asked to describe 3 dogs\n");
    for (ctr = 0; ctr < 3; ctr ++)
    {
       printf("What type (breed) of dog would you like to describe for dog #%d?\n", (ctr +1));
       gets(dog[ctr].type);
       puts("What colour is the dog? ");
       gets(dog[ctr].colour);
       puts("How many legs does the dog have? ");
       scanf(" %d", &dog[ctr].legNum);
       puts("How long is the snout of the dog in centimetres? ");
       scanf(" %.2f", &dog[ctr].snoutLen);
       getchar(); //clears last new line for the next loop
    }

Файл заголовка, как показано ниже

 struct dogInfo
{
    char type[25];
    char colour[25];
    int legNum;
    float snoutLen;
};

1 Ответ

0 голосов
/ 10 февраля 2020

Ваша проблема в том, что get ведет себя не так, как вы этого хотите. Вы не должны использовать get в любом случае, потому что это опасно и может вызвать переполнение . Но, к счастью, scanf может легко читать строки, а также позволяет указывать формат (в этом случае% 24s, потому что вы хотите прочитать до 24 символов, потому что последний символ зарезервирован для нулевого терминатора.

Код работает так:

#include <stdio.h>
struct dogInfo
{
    char type[25];
    char colour[25];
    int legNum;
    float snoutLen;
};

int main()
{
    struct dogInfo dog[3];  //Array of three structure variable
    int ctr;

    //Get information about dog from the user
    printf("You will be asked to describe 3 dogs\n");
    for (ctr = 0; ctr < 3; ctr ++)
    {
       printf("What type (breed) of dog would you like to describe for dog #%d?\n", (ctr +1));
       scanf("%24s", dog[ctr].type);
       puts("What colour is the dog? ");
       scanf("%24s", dog[ctr].colour);
       puts("How many legs does the dog have? ");
       scanf(" %d", &dog[ctr].legNum);
       puts("How long is the snout of the dog in centimetres? ");
       scanf(" %.2f", &dog[ctr].snoutLen);
       getchar(); //clears last new line for the next loop
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...