int main()
{
int num;
int num2;
printf("Enter two numbers\n");
scanf("%i\n",&num);
scanf("%i\n",&num2);
if (num % num2 == 0){
printf("%i is evenly divided by %i",num,num2);
}
else {
printf("%i is not evenly divided by %i", num, num2);
}
return 0;
}
When i run the above code in terminal this is what happens
Enter two numbers
3
4
dsfa
3 is not evenly divided by 4
I entered the two numbers, but then nothing happens until i enter some form of text(thats what the random "dsfa" is), and then the program will return with the correct printf
statement. It has to be text i cannot just hit the enter button(thats where the blank spaces come from). Why is this program not returning what i intend it to, right after the user enters two numbers?
An '\n'
or a whitespace character in the format string consumes an entire (possibly empty) sequence of whitespace characters in the input.
So the scanf
only returns when it encounters the next non-whitespace character, or the end of the input stream.
That's because the '\n'
(and this is true for any whitespace in the format string) in the format string of scanf
will match any number of whitespace characters. It will exit only when it encounters a non-whitespace character.
Also, %i
conversion specifier means that scanf
will read an integer. If the input number contains a leading 0
, the number will be read as an octal number (base 8
). If the imput number contains 0x
or 0X
, the number will be read as a hexadecimal number (in base 16
). The number will be read as decimal integer otherwise. Make sure that you really want %i
instead of %d
which always reads a decimal integer.
Please note that %i
skips leading whitespace characters anyway. So, you don't need '\n'
in the format string of scanf
to match a newline.
#include <stdio.h>
int main(void)
{
int num;
int num2;
printf("Enter two numbers\n");
scanf("%i", &num);
scanf("%i", &num2);
if (num % num2 == 0){
printf("%i is evenly divided by %i\n", num, num2);
}
else
{
printf("%i is not evenly divided by %i\n", num, num2);
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With