Adding characters at the end of a string - c

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.

Related

Some satements in for loop not executing at each iteration

#include<stdio.h>
int main()
{
int NC=0,k=0;
char mychar;
scanf("%d",&NC);
for(k=0;k < NC;k++)
{
printf("\nenter a character:-");
scanf("%c",&mychar);
printf("\n%c",mychar);
}
return 0;
}
statements below first printf statement are executing at alternative iteration of the for loop.
ie. enter image description here
When you enter a character at the keyboard, you press one key for the character, and then you press ENTER. Two characters are in the input stream: the character you enter, and a newline character. scanf() is leaving a \n character behind in the input stream. This newline character gets picked up by scanf() in the next iteration of the loop. Change to:
scanf(" %c",&mychar);
to skip over leading whitespace characters, including newlines.
To expand on this a little more, scanf() reads characters from the input stream. The %c specifier matches one character, so the second character, a \n, is left in the input stream. By adding a leading space: " %c", you are telling scanf() to first match zero or more whitespace characters (newline characters are whitespace characters, as are \t and \r), then to match another character, which is then stored in mychar. This way even when the next character to be read from the input stream is a newline character, it is skipped over. Note that most conversion specifiers automatically skip over leading whitespace characters. The ones that don't are: %c, %[], and %n.

what is the significance of newline character in the format string of scanf function?

#include<stdio.h>
int main()
{
int a,b;
printf("enter two numbers ");
scanf("%d \n%d",&a,&b);
printf("%d %d",a,b);
return 0;
}
when I give inputs like 3 and 5 , then the issue is that even if I give inputs without any newline character in between them then also the scanf function scans the input value , but in the formal string I have stated that the next input should be scanned after a newline character so how can the next input be scanned just after some few whitespaces .
White-space in the scanf format string tells scanf (and family) to read and ignore white-space in the input. It doesn't matter what kind of white-space character you use in the format: Space, newlines and tabs are all the same.
However, you don't actually need it for all formats. most scanf formats automatically reads and ignore leading white-space, including the "%d" format.
The " \n" in the "%d \n%d" format string will "eat" all whitespace characters as defined by isspace, including newlines.
To force reading the integers off separate lines, use this instead:
if(scanf("%d%*[^\n]\n%d",&a,&b) != 2) return EXIT_ERROR;

unexpected output of the following c program

the following code as expected should accept two char values from user. but it just accepts one value of ch1 and then prints "hello".
#include<stdio.h>
int main()
{
char ch1, ch2;
printf("Enter a char: ");
scanf("%c",&ch1);
printf("Enter second char: ");
scanf("%c",&ch2);
printf("Hello");
return 0;
}
it is not accepting the second value for ch2..what can be the possible reason?
As far as i think, it should accept 2 characters.
It just accepts only one char because the the first call to scanf() left a newline in the input stream.
You can ignore it with:
scanf(" %c",&ch2); // note the leading space.
This will ensure the newline from the previous input will be ignored. A white-space in the format string tells scanf() to ignore any number of white-space characters. You might also want to check the return value of scanf() calls in case it failed.
From scanf():
. 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.

Using scanf in for loop

Here is my c code:
int main()
{
int a;
for (int i = 0; i < 3; i++)
scanf("%d ", &a);
return 0;
}
When I input things like 1 2 3, it will ask me to input more, and I need to input something not ' '.
However, when I change it to (or other thing not ' ')
scanf("%d !", &a);
and input 1 ! 2! 3!, it will not ask more input.
The final space in scanf("%d ", &a); instructs scanf to consume all white space following the number. It will keep reading from stdin until you type something that is not white space. Simplify the format this way:
scanf("%d", &a);
scanf will still ignore white space before the numbers.
Conversely, the format "%d !" consumes any white space following the number and a single !. It stops scanning when it gets this character, or another non space character which it leaves in the input stream. You cannot tell from the return value whether it matched the ! or not.
scanf is very clunky, it is very difficult to use it correctly. It is often better to read a line of input with fgets() and parse that with sscanf() or even simpler functions such as strtol(), strspn() or strcspn().
scanf("%d", &a);
This should do the job.
Basically, scanf() consumes stdin input as much as its pattern matches. If you pass "%d" as the pattern, it will stop reading input after a integer is found. However, if you feed it with "%dx" for example, it matches with all integers followed by a character 'x'.
More Details:
Your pattern string could have the following characters:
Whitespace character: the function will read and ignore any whitespace
characters encountered before the next non-whitespace character
(whitespace characters include spaces, newline and tab characters --
see isspace). A single whitespace in the format string validates any
quantity of whitespace characters extracted from the stream (including
none).
Non-whitespace character, except format specifier (%): Any character that is not either a whitespace character (blank, newline or
tab) or part of a format specifier (which begin with a % character)
causes the function to read the next character from the stream,
compare it to this non-whitespace character and if it matches, it is
discarded and the function continues with the next character of
format. If the character does not match, the function fails, returning
and leaving subsequent characters of the stream unread.
Format specifiers: A sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type
and format of the data to be retrieved from the stream and stored into
the locations pointed by the additional arguments.
Source: http://www.cplusplus.com/reference/cstdio/scanf/

Make scanf pick up spaces in the middle of a string

I am trying to use scanf() for input. It worked perfectly except when I typed a space. Then it doesn't pick up the string -- why?
char idade;
scanf("%c", &idade);
I tried do to this:
scanf("%[^/n]c", &idade);
But it did not work. For example, when I typed in "Hello world", my string only contained "Hello" All I want is for it to recognize the space and take the full string. How can I do that?
The %c conversion specifier in the format string of scanf does not skip (read and discard) the leading whitespace characters. If you have a leading whitespace character in the format string, then this means scanf will skip any number of leading whitespace characters in the input which is probably what you want. Assuming you want to read a single character -
char idade;
scanf(" %c", &idade);
// ^ note the leading space
However, if you want to read an input string from stdin, then
char input[50+1]; // max input length 50. +1 for the terminating null byte
// this skips any number of leading whitespace characters and then
// reads at most 50 non-whitespace chars or till a whitespace is encountered -
// whichever occurs first, then adds a terminating null byte
scanf("%50s", input);
// if you want to read a input line from the user
// then use fgets. this reads and stores at max 50 chars
// or till it encounters a newline which is also stored - whichever
// occurs first, then it adds a terminating null byte just like scanf
fgets(input, sizeof input, stdin);
Please read the man page of fgets.
There's a small error in your line
scanf("%[^/n]c", &idade);
It should read
scanf("%[^\n]", &idade);
Backslash '\' is the escape character, not '/'.
You have to put '\n' (line feed character) in the exclusion list or else scanf will not know when to stop parsing.
Your expression excluded '/' and 'n' as input characters.

Resources