for-loop - 为什么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;
};
解决方案
你的问题是 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
}
}
推荐阅读
- angular7 - 我无法使用 Angular 7 将元标签分享到 Facebook
- git - (免费)组织中的 GitHub 私有存储库,2020 年更新
- git - 使用 `git commit --verbose` 配置选项卡宽度渲染
- java - 线程“主”java.lang.NumberFormatException 中的异常:用于输入 aaaabbaa
- c++ - 如何插入 4 个空格宽的制表符并将它们删除两个空格?
- python - 为什么 Python 整数被实现为对象?
- javascript - 从 setTimeout 检查剩余时间
- python - 如何在 django 上替换模型数据库上的元素
- node.js - 如何使用 Node js 和 MongoDB 关联两个模型?
- android - RecyclerView.SCROLL_STATE_SETTLING状态下滚动状态时需要停止滚动