问题描述
我正在用 C 编程,但在 cmd 终端中运行程序时遇到问题.这是我使用的代码:
I am programming in C and i have a problem when i run a program in the cmd terminal. here is the code i use:
#include <stdio.h>
int main() {
int num;
printf("enter a number: ");
scanf("%i\n", &num);
for(int n = 1; n < num + 1; n++){
printf("%i\n", n);
}
return 0;
}
一般来说,除了一件事,一切都像它应该的那样工作.当我输入一个数字时,没有任何反应.没有输出,直到我写任何东西并按 Enter 键,然后才会出现数字.
Generally, everything works like it should, exept for one thing. when I enter a number, nothing happens. there is no output, until I write anything and press Enter, and only then the number appear.
这是它的外观截图.这里是输入号码(然后按回车键)但没有任何反应:http://prntscr.com/deum9a
this is a screenshot of what it looks like.here is enter the number (and press enter) but nothing happens: http://prntscr.com/deum9a
这是我随机输入一些东西后所有数字弹出后的样子:http://prntscr.com/deumyn
and this is how it looks like after i entered something random nad all the numbers popped up: http://prntscr.com/deumyn
如果有人知道如何解决这个问题,请告诉我 (:
if anyone knows how to fix this, please tell me (:
推荐答案
从 scanf()
scanf("%i", &num);
当格式字符串中有空白字符时,scanf()
将忽略您输入的任意数量的空白字符,因此您执行的 ENTER 不会终止输入读取.基本上,您将被迫再次输入一个非空白字符以完成scanf()
调用.
When you have a whitespace character in the format string, scanf()
will ignore any number of whtiespaces you input and thus the ENTER you do doesn't terminate the input reading. Basically, you'll be forced to input a non whitespace character again in order complete the scanf()
call.
通常,scanf()
被认为不利于输入读取.因此,考虑使用 fgets()
并使用 sscanf()
解析输入.
Generally, scanf()
is considered bad for input reading. So, considering using fgets()
and parsing the input using sscanf()
.
这篇关于使用 scanf 的输入读取挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!