首页 > 解决方案 > 为什么for循环的第二次迭代不等待用户输入

问题描述

我遇到了 for 循环的问题。当我进行第二次迭代时,程序不会等待用户输入。任何帮助都欣然接受。

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

标签: for-loop

解决方案


你的问题是 get 没有按照你想要的方式运行。无论如何你都不应该使用gets,因为它很危险并且可能导致溢出。但幸运的是,scanf 可以轻松读取字符串并且还允许指定格式(在本例中为 %24s,因为您要读取最多 24 个字符,因为最后一个字符是为 Null 终止符保留的。

代码是这样工作的:

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

推荐阅读