problems with scanf(“%d\n”,&i) [duplicate]

巧了我就是萌 提交于 2019-11-27 07:59:47

问题


For this code:

int i;
scanf("%d\n",&i);

I am not able to stop my program until I input two numbers.

I think it is very strange ,I know when the input is suitable,the scanf will return 1. When I input "12a 'Enter'","12 'Enter'2" and so on ,it is ok,the i=12,it seems that when I input something is different int or input a 'Enter' and something another,the scanf returns 1.

What am I missing?


回答1:


"I am not able to stop my program until I input two numbers when I use scanf("%d\n",&i);"
Although this format makes scanf read the number and store it into i, this "reading" continues and it lasts till non-whitespace character followed by \n is found. This is the reason why input 1 2 makes this scanf stop.

You should not specify newline in the input format in this case. Use scanf("%d",&i); instead.




回答2:


It's because of the '\n in the scanf... If you want to move into a new line, just put :

printf ("\n");

and it'll give u an empty line...




回答3:


scanf("%d\n",&i);

read the number till non-whitespace character appear(ignore all whitespace and '\n' after the number).



来源:https://stackoverflow.com/questions/9516192/problems-with-scanfd-n-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!