int sales[ 1 ];
do
{
scanf_s( "%d", sales, 1 );
printf( "\n%d\n", sales[ 0 ] );
printf( "\nyou got weekly income of $ %d\n\n", commision( sales[ 0 ] ) );
} while ( sales[0] >-1 );
I want to ask, why every time i input int with space (example 123 456), the output is sales[0]=123 then suddenly it automatically assign 456 to sales[0], can you guys explain it why?
What your code does is that it reads a signed number from the standard input. ( %d
does read until the whitespace but ignores the whitespace itself.) It then writes that number (the first number would be 123
) to your sales
array at index 0
. Then you're writing the return value of your commision(...)
function to standard output.
then suddenly it automatically assign 456 to sales[0]
If by that you mean that at the end of the program's execution sales[0]
contains 456
instead of 123
it is because the whole procedure I described above is done as long as your do while
loop runs. And if sales[0] is greater than -1
which is the case for sales[0]
being 123
after the first procedure it will run again and read 456
from the standard input and write that to the sales
array.
Some more examples for scanf_s("%d", int_pointer, 1)
reading input from stdin
:
42 43ab 44
would be read in 3 different scanf_s
as 42
, 43
and 44
. 42 a
would be read in 2 different scanf_s
as 42
and 0
. 42 a a43 44
would be read in 4 different scanf_s
as 42
, 0
, 0
and 44
. Because scanf is picky and it wants the exact input of one number. To it the whitespace signals the end of the desired input format.
123[whitespace] -> 123 is assigned, stuff happens, loops again.
456[whitespace] -> 456 is assigned, stuff happens, loops again.
int commission(int i) {
return 42*i;
}
int main(int argc, const char * argv[]) {
int sales[ 1 ];
do
{
scanf_s( "%d", sales, 1 );
printf( "\n%d\n", sales[ 0 ] );
printf( "\nyou got weekly income of $ %d\n\n", commission( sales[ 0 ] ) );
sales[0] = -1; // Won't jump to the next value
} while ( sales[0] >-1 ); // But then what's the point of the loop?
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.