【问题标题】:Can't enter name gets无法输入名称获取
【发布时间】:2021-10-06 13:51:55
【问题描述】:
#include<stdio.h>
#include<stdlib.h>

struct student {
    char name[30];
};
typedef struct student sv;
int main() {
    int i;
    sv basedata[50] ;
    int totalstudent;
    do
    {
        printf("How many people are there: ");
        scanf_s("%i", &totalstudent);
    } while (totalstudent<0);
    fflush(stdin);
    for ( i = 0; i < totalstudent; i++)
    {
        printf("Person %i name: ", i + 1);
        gets(basedata[i].name);
    }
}

输出: 有多少人:1 第 1 个人姓名:
D:\hello\chuong7\x64\Debug\chuong6.exe(进程 26572)以代码 0 退出。 按任意键关闭此窗口。 .

为什么我在运行我的程序时不能输入第 1 个人的名字,我的程序传递到结束并且我不能得到(basedata[i].name)。对不起,我只是学英语 picture here

【问题讨论】:

标签: c


【解决方案1】:

这个程序有很多错误,但特别让您感到困惑的是您正在调用scanf,它不会读取行中的输入,然后是gets确实。在scanf 之后,用户在数字后面键入的回车仍在等待读取。 gets 读取的是回车符,而不是您尝试提示的其他输入。您拨打fflush(stdin) 不会改变这一点; what fflush(stdin) does, varies from system to system, but it never does what people seem to expect it to do.

此外,gets is dangerous and should never be usedscanf is broken-as-specified and should never be usedall of the _s functions that Microsoft's compilers like to push on you are unportable and don't fix the problems Microsoft was trying to solve, and (wait for it) should never be used

你应该这样做:

  1. #define _CRT_SECURE_NO_WARNINGS 1 放在文件的顶部(在所有#includes 之前),以使MSVC 不再给你不好的建议。
  2. 使用fgets 读取用户输入的所有行。
  3. 使用strtol 将输入的十进制数转换为机器整数。
  4. 由于您使用的是静态分配的记录数组,因此在进入循环之前检查输入的数字是否大于数组的大小。

祝你好运。

【讨论】:

  • 好答案,这似乎完全符合我在这里的答案:Which functions from the standard library must (should) be avoided? 虽然今天我可能也会添加所有_s 函数,但在 C11“边界检查接口”尝试变成惨败。也可以在同一篇文章中对声称“已弃用,因为微软这么说”的其他答案进行投票...... :)
  • 我还写了一篇关于微软神话和strcpy的帖子,特别是在这里:Is strcpy dangerous and what should be used instead?
  • 你好 ZWOL,我看到了一些编译器警告,一些函数、类成员、变量或 typedef 在 Visual Studio 中被标记为已弃用。你能帮我了解一下吗?,我发现很多功能已被弃用,但我发现一些网站的信息仍在使用。
  • @AnNguyen 请就此提出一个新问题。确保显示所有错误的完整且未经编辑的文本。您可能会被要求提供“MCVE”:请参阅stackoverflow.com/help/mcve
  • @zwol textcolor()、textbackground() 和 clrscr 怎么样;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 2018-02-21
  • 1970-01-01
相关资源
最近更新 更多