I am trying to add some characters at the end of a string using the following code. I am not getting the desired output.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int l,i;
char a[30];
printf("Enter \n");
scanf("%s",a);
l=strlen(a);
for(i=l;i<(29-l);i++)
{
scanf("%c",&a[i]);
a[i+1]='\0';
printf("\n%s",a);
}
return 0;
}
I guess, the problem is with whitespace. After you enter the first string, there is still a newline \\n
in the input buffer. When you then read one character with scanf
, you get the newline and not the character you entered.
You can skip the whitespace, when you prefix the format string with a space
scanf(" %c",&a[i]);
Now it will append the character entered at the end of the string.
Update:
From scanf
The format string consists of a sequence of directives which describe how to process the sequence of input characters.
...
• A sequence of white-space characters (space, tab, newline, etc.; see isspace(3)). This directive matches any amount of white space, including none, in the input.
This means, when you insert a space in the format string, it will skip all white-space in the input.
This will happen automatically with other input directives like %s
or %d
. But %c
takes the next character, even if it is a white-space char. Therefore, if you want to skip white-space in this case, you must tell scanf
by inserting a space in the format string.
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.