Related
What is difference between scanf("%d") and scanf("%d ") in this code, where the difference is the trailing blank in the format string?
#include <stdio.h>
int main(void)
{
int i, j;
printf("enter a value for j ");
scanf("%d ",&j);
printf("j is %d\n", j);
printf("enter a value for i ");
scanf("%d", &i);
printf("i is %d\n", i);
return 0;
}
How does the scanf() function actually work when I add spaces after the format specifier like scanf("%d ", &j);?
A whitespace character in a scanf format causes it to explicitly read and ignore as many whitespace characters as it can. So with scanf("%d ", ..., after reading a number, it will continue to read characters, discarding all whitespace until it sees a non-whitespace character on the input. That non-whitespace character will be left as the next character to be read by an input function.
With your code:
printf("enter a value for j ");
scanf("%d ",&j);
printf("j is %d \n", j);
it will print the first line and then wait for you to enter a number, and then continue to wait for something after the number. So if you just type 5Enter, it will appear to hang — you need to type in another line with some non-whitespace character on it to continue. If you then type 6Enter, that will become the value for i, so your screen will look something like:
enter a value for j 5
6
j is 5
enter a value for i i is 6
Also, since most scanf %-conversions also skip leading whitespace (all except for %c, %[ and %n), spaces before %-conversions are irrelevant ("%d" and " %d" will act identically). So for the most part, you should avoid spaces in scanf conversions unless you know you specifically need them for their peculiar effect.
A white-space character (space, newline, horizontal and vertical tab) in a format string matches any number of white-space characters in the input.
In your first case
scanf("%d ",&j);
when it encounters the white-space char (WSC) ' ' then it will eat all the white spaces input by user including \n on pressing Enter and it will expect to enter a non-WSC . In this case your program will terminate by pressing Ctrl + Z.
A whitespace character in your scanf format matches any number of whitespace characters as described by isspace. So if you have tailing spaces, newlines, tabulators or any other whitespace character then it will also be consumed by scanf before it returns.
The difference (although obvious) is a different format string. If you enter the following line:
"3 "
scanf() will return successfully. Otherwise, it depends on your input provided. scanf() essentially skips over whitespace (tabs, spaces, newlines), and searches for alphanumeric values in the input stream. Since this is trailing whitespace, it gets lumped in with the trailing newline character at the end of input when pressing ENTER, so it's of little consequence.
scanf() expects the input provided to exactly match the format string you provide to it, with the exception that contiguous whitespace characters are compressed to a single whitespace character. This becomes very important if you want to parse large strings of data with it's string-processing equivalent, sscanf().
A good exercise to further test this would be something like:
#include<stdio.h>
int main(void)
{
int a=0,b=0,c=0;
printf("Enter values for A, B, C, in the format: \"A B - C\"\n");
scanf("%d %d - %d", &a, &b, &c);
printf("Values: A:%d, B:%d, C:%d\n", a, b, c);
}
Afterwards, check and see what the values of these integers are after providing both correctly and incorrectly formatted consoled input (ie: spaces and hyphens). Here are a couple example runs. The first used incorrect input, the second used correctly formatted input. Notice that in the first case, C doesn't even get set, as scanf() will provided unexpected behavior if the input and the format strings don't match up. In general, you are better off using something like fgets() to get a string of input from the user, and then use various search functions (ie: strstr(), strch(), strcat, strcpy, etc) to parse your string, as it is much safer than just using scanf() and assuming the user won't make a mistake, either accidentally or deliberately.
Enter values for A, B, C, in the format: "A B - C"
1 2 3
Values: A:1, B:2, C:0
Enter values for A, B, C, in the format: "A B - C"
1 2 - 3
Values: A:1, B:2, C:3
Now, consider one last run: You'll see that scanf() compacts multiple consecutive whitespace characters to a single character, hence why these final runs actually succeeds:
Enter values for A, B, C, in the format: "A B - C"
1 2 - 3
Values: A:1, B:2, C:3
Enter values for A, B, C, in the format: "A B - C"
1 2 - 3
Values: A:1, B:2, C:3
What is difference between scanf("%d") and scanf("%d ") in this code, where the difference is the trailing blank in the format string?
#include <stdio.h>
int main(void)
{
int i, j;
printf("enter a value for j ");
scanf("%d ",&j);
printf("j is %d\n", j);
printf("enter a value for i ");
scanf("%d", &i);
printf("i is %d\n", i);
return 0;
}
How does the scanf() function actually work when I add spaces after the format specifier like scanf("%d ", &j);?
A whitespace character in a scanf format causes it to explicitly read and ignore as many whitespace characters as it can. So with scanf("%d ", ..., after reading a number, it will continue to read characters, discarding all whitespace until it sees a non-whitespace character on the input. That non-whitespace character will be left as the next character to be read by an input function.
With your code:
printf("enter a value for j ");
scanf("%d ",&j);
printf("j is %d \n", j);
it will print the first line and then wait for you to enter a number, and then continue to wait for something after the number. So if you just type 5Enter, it will appear to hang — you need to type in another line with some non-whitespace character on it to continue. If you then type 6Enter, that will become the value for i, so your screen will look something like:
enter a value for j 5
6
j is 5
enter a value for i i is 6
Also, since most scanf %-conversions also skip leading whitespace (all except for %c, %[ and %n), spaces before %-conversions are irrelevant ("%d" and " %d" will act identically). So for the most part, you should avoid spaces in scanf conversions unless you know you specifically need them for their peculiar effect.
A white-space character (space, newline, horizontal and vertical tab) in a format string matches any number of white-space characters in the input.
In your first case
scanf("%d ",&j);
when it encounters the white-space char (WSC) ' ' then it will eat all the white spaces input by user including \n on pressing Enter and it will expect to enter a non-WSC . In this case your program will terminate by pressing Ctrl + Z.
A whitespace character in your scanf format matches any number of whitespace characters as described by isspace. So if you have tailing spaces, newlines, tabulators or any other whitespace character then it will also be consumed by scanf before it returns.
The difference (although obvious) is a different format string. If you enter the following line:
"3 "
scanf() will return successfully. Otherwise, it depends on your input provided. scanf() essentially skips over whitespace (tabs, spaces, newlines), and searches for alphanumeric values in the input stream. Since this is trailing whitespace, it gets lumped in with the trailing newline character at the end of input when pressing ENTER, so it's of little consequence.
scanf() expects the input provided to exactly match the format string you provide to it, with the exception that contiguous whitespace characters are compressed to a single whitespace character. This becomes very important if you want to parse large strings of data with it's string-processing equivalent, sscanf().
A good exercise to further test this would be something like:
#include<stdio.h>
int main(void)
{
int a=0,b=0,c=0;
printf("Enter values for A, B, C, in the format: \"A B - C\"\n");
scanf("%d %d - %d", &a, &b, &c);
printf("Values: A:%d, B:%d, C:%d\n", a, b, c);
}
Afterwards, check and see what the values of these integers are after providing both correctly and incorrectly formatted consoled input (ie: spaces and hyphens). Here are a couple example runs. The first used incorrect input, the second used correctly formatted input. Notice that in the first case, C doesn't even get set, as scanf() will provided unexpected behavior if the input and the format strings don't match up. In general, you are better off using something like fgets() to get a string of input from the user, and then use various search functions (ie: strstr(), strch(), strcat, strcpy, etc) to parse your string, as it is much safer than just using scanf() and assuming the user won't make a mistake, either accidentally or deliberately.
Enter values for A, B, C, in the format: "A B - C"
1 2 3
Values: A:1, B:2, C:0
Enter values for A, B, C, in the format: "A B - C"
1 2 - 3
Values: A:1, B:2, C:3
Now, consider one last run: You'll see that scanf() compacts multiple consecutive whitespace characters to a single character, hence why these final runs actually succeeds:
Enter values for A, B, C, in the format: "A B - C"
1 2 - 3
Values: A:1, B:2, C:3
Enter values for A, B, C, in the format: "A B - C"
1 2 - 3
Values: A:1, B:2, C:3
What is difference between scanf("%d") and scanf("%d ") in this code, where the difference is the trailing blank in the format string?
#include <stdio.h>
int main(void)
{
int i, j;
printf("enter a value for j ");
scanf("%d ",&j);
printf("j is %d\n", j);
printf("enter a value for i ");
scanf("%d", &i);
printf("i is %d\n", i);
return 0;
}
How does the scanf() function actually work when I add spaces after the format specifier like scanf("%d ", &j);?
A whitespace character in a scanf format causes it to explicitly read and ignore as many whitespace characters as it can. So with scanf("%d ", ..., after reading a number, it will continue to read characters, discarding all whitespace until it sees a non-whitespace character on the input. That non-whitespace character will be left as the next character to be read by an input function.
With your code:
printf("enter a value for j ");
scanf("%d ",&j);
printf("j is %d \n", j);
it will print the first line and then wait for you to enter a number, and then continue to wait for something after the number. So if you just type 5Enter, it will appear to hang — you need to type in another line with some non-whitespace character on it to continue. If you then type 6Enter, that will become the value for i, so your screen will look something like:
enter a value for j 5
6
j is 5
enter a value for i i is 6
Also, since most scanf %-conversions also skip leading whitespace (all except for %c, %[ and %n), spaces before %-conversions are irrelevant ("%d" and " %d" will act identically). So for the most part, you should avoid spaces in scanf conversions unless you know you specifically need them for their peculiar effect.
A white-space character (space, newline, horizontal and vertical tab) in a format string matches any number of white-space characters in the input.
In your first case
scanf("%d ",&j);
when it encounters the white-space char (WSC) ' ' then it will eat all the white spaces input by user including \n on pressing Enter and it will expect to enter a non-WSC . In this case your program will terminate by pressing Ctrl + Z.
A whitespace character in your scanf format matches any number of whitespace characters as described by isspace. So if you have tailing spaces, newlines, tabulators or any other whitespace character then it will also be consumed by scanf before it returns.
The difference (although obvious) is a different format string. If you enter the following line:
"3 "
scanf() will return successfully. Otherwise, it depends on your input provided. scanf() essentially skips over whitespace (tabs, spaces, newlines), and searches for alphanumeric values in the input stream. Since this is trailing whitespace, it gets lumped in with the trailing newline character at the end of input when pressing ENTER, so it's of little consequence.
scanf() expects the input provided to exactly match the format string you provide to it, with the exception that contiguous whitespace characters are compressed to a single whitespace character. This becomes very important if you want to parse large strings of data with it's string-processing equivalent, sscanf().
A good exercise to further test this would be something like:
#include<stdio.h>
int main(void)
{
int a=0,b=0,c=0;
printf("Enter values for A, B, C, in the format: \"A B - C\"\n");
scanf("%d %d - %d", &a, &b, &c);
printf("Values: A:%d, B:%d, C:%d\n", a, b, c);
}
Afterwards, check and see what the values of these integers are after providing both correctly and incorrectly formatted consoled input (ie: spaces and hyphens). Here are a couple example runs. The first used incorrect input, the second used correctly formatted input. Notice that in the first case, C doesn't even get set, as scanf() will provided unexpected behavior if the input and the format strings don't match up. In general, you are better off using something like fgets() to get a string of input from the user, and then use various search functions (ie: strstr(), strch(), strcat, strcpy, etc) to parse your string, as it is much safer than just using scanf() and assuming the user won't make a mistake, either accidentally or deliberately.
Enter values for A, B, C, in the format: "A B - C"
1 2 3
Values: A:1, B:2, C:0
Enter values for A, B, C, in the format: "A B - C"
1 2 - 3
Values: A:1, B:2, C:3
Now, consider one last run: You'll see that scanf() compacts multiple consecutive whitespace characters to a single character, hence why these final runs actually succeeds:
Enter values for A, B, C, in the format: "A B - C"
1 2 - 3
Values: A:1, B:2, C:3
Enter values for A, B, C, in the format: "A B - C"
1 2 - 3
Values: A:1, B:2, C:3
Here is my code to repeatedly read three variables separated by whitespace from user. The format of input should be 'char int int'(e.g b 3 3 ). I use the return value of scanf function to ensure input is exactly three variables.
#include <stdio.h>
int main(void){
int x, y, nargs;
char command;
while(1){
nargs = scanf("%c %d %d", &command, &x, &y);
printf("%d\n",nargs);
if(nargs != 3){
printf("error\n");
break;
}
}
return 0;
}
Input and Output:
g 4 4
3
b 3 3
1
error
The first line input is no problem. But when I input second line, it shows scanf() only read one variable from this line. What's the problem of my code?
The problem is the \n newline hidden between the two input lines you are sending to stdin. After first scanf you have a '\n' pending on the input stream, then you append "b 3 3" so the whole buffer looks like "\nb 3 3".
Then scanf is called again and \n is matched to %c, after scanf expects whitespace but the buffer has 'b' so it fails after assigning \n to command.
You could try matching with
nargs = scanf("%c %d %d ", &command, &x, &y);
^
so that newline is eaten with the previous scanf, from cppreference:
any single whitespace character in the format string consumes all available consecutive whitespace characters from the input
nargs = scanf("%1s %d %d", &command, &x, &y);
The problem is with the %c for one character. If you change it for %1s you expect an string of one character (the same) but without problems.
With the %c it is better to send the result to an array, and access the content with its index.
I tried a simple program..function returning integer and character pointer..after i run that code i found some weird acting by scanf..I tried to print message(enter a,b:) read two integer inputs and message(enter c,d:) read two char inputs.but at run time..i found that input for the char c is read rightafter i enter the inputs for a,b..
for eg:
enter a,b: 10
20
enter c,d: g
it gets only one input(for d) and input for c is newline after 20..
for eg 2:
enter a,b: 10
20a
enter c,d: g
it gets only one input(for d) and input for c is a after 20..
why is this happening..please clarify it
int* add(int *a,int *b)
{
return (*a>*b?a:b);
}
char* charret(char *c,char *d)
{
return (*c>*d?c:d);
}
int main()
{
int a,b;
char c,d;
printf("\n\t\tFUNCTION RETURNING INTEGER POINTER\n\t");
printf("Enter the Number A and B:");
scanf("%d %d",&a,&b);
printf("\tEnter the character c :");
scanf("%c %c",&c,&d);
printf("The Biggestt Value is : %d\n\t",*add(&a,&b));
printf("\n\tThe character c= %c hi d= %c",c,d);
// scanf("%c",&d);
printf("\n\tThe Biggestt Value is : %c", *charret(&c,&d));
getch();
return 0;
}
%c will read any character, including the newline character from your previous entry. If you want to read the first non-whitespace character, add a space before %c in your format string:
scanf(" %c %c",&c,&d);
/* ^ added space */
This will cause scanf() to eat any number of whitespaces before reading the character.
For most scanf() specifiers, any leading whitespace is skipped. %c is an exception to this, because it reads a single character value, including whitespace characters. Keep in mind when you press Enter, you've sent a '\n' to the input buffer.
scanf("%d %d",&a,&b);
Reads in two numbers. The \n at the end, from pressing Enter, is left in the buffer.
scanf("%c %c",&c,&d);
Reads in two characters, the first of which will be the \n left in the buffer. One way to get around this is:
while (getch() != '\n');
This will eat everything up to an including a newline. You can put that after the scanf() lines you know will leave a newline behind.