[英]C scanf skipping second time
I have read about placing whitespace in front of scanf but I everything I try does not work. 我已经读过有关在scanf前面放置空格的信息,但是我尝试的所有方法均无效。 I am trying to read in two sets of three integers.
我试图读取两组三个整数。 The first scanf works fine while the second does not.
第一个scanf可以正常工作,而第二个则不能。 I am frustrated because I try everything that I see in forums with placing spaces in front or newline characters and nothing works.
我很沮丧,因为我尝试在论坛中看到的所有内容都在空格或换行符前加了空格,但没有任何效果。
Code in question: 有问题的代码:
// Get user input for the two dates:
printf("Enter Date #1 in format mm:dd:yyyy \n");
scanf("%i:%i:%i\n", &D1.month, &D1.day, &D1.year);
printf("Enter Date #2 in format mm:dd:yyyy\n");
scanf("%i:%i:%i", &D2.month, &D2.day, &D2.year);
I tried to put a space AND a newline character in there separatly and together, I tried to read in a dummy variable character to see if that would work. 我试图将空格和换行符分开放置在一起,试图读取一个虚拟变量字符以查看是否可行。 Why can I not enter any data in the second scanf??
为什么在第二个scanf中不能输入任何数据?
The output is shown: 输出显示为:
Enter Date #1 in format mm:dd:yyyy
09:06:1995
Enter Date #2 in format mm:dd:yyyy
The number of days between 0:1529117256:94769206 and 9:6:1995 is -1783102426
I make a new post because I see explanations with characters but not with integers. 我发表了一篇新文章,因为我看到了有关字符而不是整数的解释。
When you use %i
with scanf
: 当您将
%i
与scanf
:
scanf("%i",&inp); //INPUT 09 AS MONTH OR ANYTHING
It will read input as octal due the prefixed 0
or leading zero when input is 09
, hence the value of inp
becomes invalid since 9
is not a valid octal digit, octal digits being 0,1,2,3,4,5,6,7
. 输入为
09
,它将以前缀0
或前导零作为八进制输入,因此inp
的值将无效,因为9
不是有效的八进制数字,八进制数字为0,1,2,3,4,5,6,7
。
Where as in case when %d
is being used than 09
input will not be converted into octal and the value read will be 9
. 就像使用
%d
时一样,输入09
不会转换为八进制 ,读取的值为9
。
Apart from this there is something I would like to suggest: away-from-scanf 除此之外,我还想提出一些建议: 远离scanf
As given in comment (1) by user3121023 changin both to "%d" 's instead of "%i" 's fixed the issue. 如user3121023的注释(1)所述,将两者都更改为“%d”而不是“%i”修复了该问题。 I am unclear why.
我不清楚为什么。
Code is now: 现在的代码是:
// Get user input for the two dates:
printf("Enter Date #1 in format mm:dd:yyyy \n");
scanf("%d:%d:%d", &D1.month, &D1.day, &D1.year);
printf("Enter Date #2 in format mm:dd:yyyy\n");
scanf("%d:%d:%d", &D2.month, &D2.day, &D2.year);
In addition: 此外:
"%d:%d:%d\n"
would not work. 将无法正常工作。 Do not put '\\n' in your scanf.
不要在您的scanf中输入'\\ n'。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.