为什么我的字符串输入不被接受 [英] Why is my string input not being accepted

查看:196
本文介绍了为什么我的字符串输入不被接受的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>
#include<conio.h>
#include<string.h>


struct est
{
int sno;
};

void main()
{
struct est s1;
char name[40];

printf("enter a number\n");
scanf("%d", &s1.sno);

printf("Name?\n");
fgets(name, 40, stdin);
getch();
}





我是C中的一个完整的菜鸟,我真的需要帮助。

第一个输入正常,但在打印名称?之后,只要按任意键,它就会退出(在橙色C IDE中)或显示等效的ASCII(Pelles C,虽然我确定它实际上只是放弃了)

没有我使用第一个scanf不确定为什么它工作正常。

非常感谢任何帮助:^)



我尝试了什么:



我也尝试过gets()但是徒劳无功。



I'm a complete noob in C and i really need help.
The first input goes fine, but after it prints Name? as soon as i press any key it either quits (in orange C IDE) or shows the equivalent ASCII (Pelles C, though I'm sure it is actually just quitting)
It works fine without me using the first scanf not sure why.
Any help is greatly appreciated :^)

What I have tried:

I have tried gets() too but in vain.

推荐答案

这是因为你的 scanf()调用在没有按ENTER键时生成新行字符的情况下读取输入。所以这个新行字符仍然在输入缓冲区中。 fgets()调用将从输入读取,直到出现新的行字符。但那已经存在,所以它会立即返回。



之前已经提出这个问题,可以在网上找到多个答案和解决方案,例如c - fgets指令被跳过。为什么? - 堆栈溢出 [ ^ ]。



一般情况下,你不应该使用 scanf()进行键盘输入。最好使用 fgets()编写输入例程,解析字符串以检查它是否与所需格式匹配,并在成功时将其转换为目标类型(例如,使用 atoi() strtol() for integers)。
That is beacuse your scanf() call reads the input without the new line character generated when pressing the ENTER key. So this new line character is still in the input buffer. The fgets() call will read from the input until a new line character is present. But that is already there and so it returns immediately.

This has been asked before and multiple answers and solutions can be found in the web like at c - fgets instructions gets skipped.Why? - Stack Overflow[^].

In general you should not use scanf() for keyboard input. It is better to write an input routine using fgets(), parse the string to check if it matches the required format, and convert it to the destination type upon success (e.g. using atoi() or strtol() for integers).


这篇关于为什么我的字符串输入不被接受的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆