Problems with scanf ("% d \ n", & i)

For this code:

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

I cannot stop my program until I enter two numbers.

I think this is very strange, I know when the input comes up, scanf will return 1. When I enter "12a 'Enter'", "12" Enter'2 "etc. This is normal, I = 12, it seems that when I entered something else int or entered a 'Enter' and something else, scanf returns 1.

What am I missing?

+4
source share
3 answers

"I cannot stop my program until I enter two numbers when using scanf("%d\n",&i); "
Although this format allows scanf to read the number and store it in i , this β€œreading” continues and continues until a character with no spaces is found, followed by \n . That is why input 1 2 stops this scanf .

In this case, you should not specify a new line in the input format. Use scanf("%d",&i); instead .

+14
source

This is because of '\n in scanf ... If you want to jump to a new line, just put:

 printf ("\n"); 

and he will give an empty string ...

+3
source

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

read the number before the character appears without spaces (ignore all spaces and "\ n" after the number).

0
source

Source: https://habr.com/ru/post/1399171/


All Articles