如何在 C 中获得多个 scanf 或 getchar 提示?
我正在尝试编写一个 C 程序,但由于某种原因我无法使用多个 scanf 或 getchar 提示符。我希望它看起来像这样:
"Please enter the first number:"
[user enters number]
"Please enter the second number:"
[user enters number]
但目前,它跳过第二个提示。我正在使用一个简单的
scanf("%d", 第一个),
以及
scanf("%d", 第二个)。
有人可以告诉我我做错了什么吗?
I'm trying to write a C program, but for some reason I can't use more than one scanf or getchar prompt. I want it to look something like this:
"Please enter the first number:"
[user enters number]
"Please enter the second number:"
[user enters number]
But currently, it skips the second prompt. I'm using a simple
scanf("%d", first),
and
scanf("%d", second).
Can someone tell me what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该在第一次 scanf() 之后使用 fflush (stdin) 清理缓冲区。或者您可以使用 getchar()。
您可以在此处找到更多说明:http://www.phanderson.com/C/scanf.html< /a>
You should clean the buffer after the first scanf(), using fflush (stdin). Or you could use getchar().
You can find further explanations here: http://www.phanderson.com/C/scanf.html
问题是,当您在命令行输入第一个值时,您实际上在 stdin 缓冲区中放入了 2 个字符,即您想要的字符和 LF 字符。
人们普遍认为最好使用 fgets(char *s, int n, FILE *stream),其中 *stream 是 stdin,*s 是 char 数组,n 是要读取的最大字符数。这使您可以更好地控制读入的字节数,以防止溢出错误。在本例中它是 2,因为它是您想要的字符加上 LF 字符。 C 中的字符串以 null 结尾,因此您至少需要一个 3 字节数组来保存一个字符。要访问所需的一个字符,只需从传递给 fgets 的数组的 0 索引中读取即可。
前任:
The problem is that when you input the first value at the command line, you actually put 2 characters in the stdin buffer, the character you want and the LF character.
It is generally accepted that you are better off using fgets(char *s, int n, FILE *stream), where *stream is stdin, *s is a char array, and n is the maximum number of characters to read. This gives you more control over the number of bytes read in to prevent overflow errors. In this case it is 2 because it is the character you want plus the LF character. Strings in C are null terminated so you will need at least a 3 byte array to hold one character. To access the one character you want, just read from the the 0 index of the array you passed to fgets.
Ex: