[英]Why scanf doesn't work with spaces at the end of formal input?
I'm trying this:我正在尝试这个:
int M,N,K;
printf("Enter (m,k,n) : ");
scanf("%d %d %d ", &M, &K, &N);
printf("\nDone?");
This is inside the main function.这是主function内部。 I need the program to read the three integers but when I run it, it just reads the three but doesn't go past the scanf, ie "Done?"我需要程序来读取三个整数,但是当我运行它时,它只读取三个但 go 没有通过 scanf,即“完成?” isn't executed, as if it's still waiting for more input.没有被执行,就好像它还在等待更多的输入。 If I remove the space after the last %d, it works fine.如果我在最后一个 %d 之后删除空间,它工作正常。 But why is that so?但为什么会这样呢?
If I remove the space after the last %d, it works fine.如果我在最后一个 %d 之后删除空间,它工作正常。 But why is that so?但为什么会这样呢?
" "
in "%d %d %d "
directs scanf()
to read, and not save, any number of whites-spaces including '\n'
. " "
in "%d %d %d "
指示scanf()
读取而不是保存任意数量的空格,包括'\n'
。
scanf()
keeps consuming white-spaces until some non-white-space in encountered. scanf()
不断消耗空白,直到遇到一些非空白。 @user3121023 @user3121023
"%d %d %d "
obliges scanf()
to not return until some non-white-space is read after the 3 numbers. "%d %d %d "
强制scanf()
在 3 个数字之后读取一些非空白之前不返回。
Tip: Avoid scanf()
.提示:避免scanf()
。 Use fgets()
and then parse the string .使用fgets()
然后解析字符串。 @DevSolar @DevSolar
Here is the way to take user inputs in multiple variables:以下是在多个变量中获取用户输入的方法:
int M,N,K;
printf("Enter (m,k,n) : ");
scanf("%d", &M);
scanf("%d", &N);
scanf("%d", &K);
printf("\nDone?");
Try to read the values separately.尝试分别读取这些值。 I don't think that scanf is intended to be used this way.我不认为 scanf 打算以这种方式使用。 Also, what you're expecting putting a blank space at the end of scanf's string?另外,您期望在 scanf 字符串的末尾放置一个空格是什么? Try this:尝试这个:
scanf("%d", &M);
scanf("%d", &K);
scanf("%d", &N);
EDIT: I checked it out, and yeah, you can do that.编辑:我检查了,是的,你可以这样做。 But why you would want to do that way?但是你为什么要这样做呢? It will be harder to validate if the user input is incorrect, like with a blank space or a non intended char.如果用户输入不正确,例如空格或非预期字符,将更难验证。 You could read this as a full string with fgets()
and the tokenize it with strtok()
, if you're expecting everything in a single text line.如果您希望所有内容都在单个文本行中,则可以使用fgets()
将其读取为完整字符串并使用strtok()
对其进行标记。 Or simply read the values separately as showed.或者只是如图所示单独读取值。
Well, just my opinion, tho.好吧,只是我的意见,寿。 If I'm wrong, please someone clarify me.如果我错了,请有人澄清我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.