Why 2nd scanf doesn't work in my program? - c

scanf("%d %c",&size,&chara); works but separate scanf for character input does not work. I show these inside the code. Why is that?
void squareCustomFill(int size, char chara);
int main(void) {
int size,i,k;
char chara;
printf("Enter size of square: "); //This works
scanf("%d %c",&size,&chara);
//printf("Enter fill character: "); BUT WHY DOES NOT THIS WORK??
//scanf("%c",&chara);
squareCustomFill(size,chara);
return 0;
}
void squareCustomFill(int size, char chara){
int i,k;
for (k=1;k<=size;k++){
for(i=1;i<=size;i++)
printf("%c",chara);
printf("\n");
}
}

Scanf did not consume the \n character that stayed in the buffer from the first scanf call.
So the second scanf call did.
You have to clear the stdin before reading again or just get rid of the newline.
The second call should be
scanf(" %c",&chara);
^ this space this will read whitespace charaters( what newline also is) until it finds a single char

Yes I believe Armin is correct. scanf will read in whitespace (spacebar, newline, etc.). When you're inputting values if you click the space bar or enter right after the first scanf, the second scanf will read in that value (space, newline, etc.). So you fixed that with scanf("%d %c",&size,&chara) because there is a space between %d and %c. If you want them separate just do what Armin suggested: scanf(" %c",&chara).

Throw a getchar() in between them and slurp up that extraneous newline.

Related

Not able to change the value of the char variable

#include<stdio.h>
#include<conio.h>
void main()
{
char c;
int i;
clrscr();
scanf("%c",&c);
scanf("%c",&c);
printf("%c",c);
getch();
}
This program does not takes the value of the char c for the second time however it works fine in the case of the integer variable. Why so?
Add in an extra space before %c:
scanf(" %c",&c);
This is because in the previous scanf, you entered the character, and then a newline \n. Thus, in the first scanf, the character was stored, and in the second scanf the newline was stored.
Alternatively, you can use getchar to store the newline. Add getchar() before the second scanf and after the first scanf.
It's because when you enter the first character, you probably end it with a newline, and that newline is still in the input buffer so the next scanf call will read that newline. So when you print it, it prints a newline.
You can tell scanf to discard leading whitespace by adding a single space before the format: " %c".

char Input in C by scanf

Help me Please.
I want to know why it happen.
This code is not give right answer:
#include < stdio.h>
int main()
{
char c,ch;
int i;
printf("Welcome buddy!\n\nPlease input first character of your name: ");
scanf("%c",&c);
printf("\nPlease input first character of your lovers name: ");
scanf("%c",&ch);
printf("\nHow many children do you want? ");
scanf("%d",&i);
printf("\n\n%c loves %c and %c want %d children",c,ch,c,i);
return 0;
}
but this code give right answer.
#include < stdio.h>
int main()
{
char c,ch;
int i;
printf("Welcome buddy!\n\nPlease input first character of your name: ");
scanf(" %c",&c);
printf("\nPlease input first character of your lovers name: ");
scanf(" %c",&ch);
printf("\nHow many children do you want? ");
scanf("%d",&i);
printf("\n\n%c loves %c and %c want %d children",c,ch,c,i);
return 0;
}
Why?
and How?
Please help me anyone who know this why it happend.
While you are giving like this, It will not ignore the white spaces.
scanf("%c",&ch);
When you are giving the input to the first scanf then you will give the enter('\n'). It is one character so it will take that as input to the second scanf. So second input will not get input from the user.
scanf(" %c",&ch);
If you give like this, then it will ignore that white space character, then it will ask for the input from the user.
The first program doesn't work properly, because the scanf function when checking for input doesn't remove automatically whitespaces when trying to parse characters.
So in the first program the value of c will be a char and the value of ch will be the '\n' (newline) char.
Using scanf("\n%c", &varname); or scanf(" %c", &varname); will parse the newline inserted while pressing enter.
The scanf function reads data from standard input stream stdin.
int scanf(const char *format, …);
The white-space characters in format, such as blanks and new-line characters, causes scanf to read, but not store, all consecutive white-space characters in the input up to the next character that is not a white-space character.
Now, when you press, by example, "a" and "return", you have two chars in the stdin stream: a and the \n char.
That is why the second call to scanf assign the \n char to ch var.
your scanf() function takes input from stdin. Now when you hit any character from keyboard and hit enter, character entered by you is scanned by scanf() but still enter is present in stdin which will be scanned by scanf() below it. To ignore white spaces you have to use scanf() with " %c".

Simple C code not working

I have written a simple code to check whether a given character is present in the string entered by the user but it doesn't seem to work.
#include<stdio.h>
#include<string.h>
int main()
{
char a[20],b;
int i,p=0,n;
printf("Enter the string-");
scanf("%s",a);
printf("\nEnter the character-");
scanf("%c",&b);
n=strlen(a);
for(i=0;i<n;i++)
{
if(a[i]==b)
{
printf("\ncharacter is present in string\n");
p=1;
break;
}
}
if(p==0)
printf("\nchracter is not present in string\n");
return 0;
}
The output I get is this: http://i58.tinypic.com/2gvnedt.png
I do not see what is wrong with the code. If I replace "scanf("%s",a);" with "gets(a);" it works fine. Why?
Help is appreciated. Thanks!
Add a space character in:
scanf(" %c",&b);
^
To consume the trailing \n character that is left in stdin after the first scanf.
So a \n is left in the standard input from which scanf is reading. So when a new scanf is met it scans the old \n character.
To neutralize that effect I put a space character in scanf i.e. I am telling it to expect to read a \n or space or \t and then to read a %c.

Scanf for string not working correctly

when i m running this code.Code was supposed to ask for second scanf string.But it is printing some garbage value..Please explain this why this is happening??
int main()
{
char arr[50];
int ll;
char sb[20];
printf("enter the string\n");
scanf("%[^\n]s",arr);
printf("string=%s\n",arr);
printf("\n enter sub");
scanf("%[^\n]s",sb);
printf("\n sub-string=%s",sb);
return 0;
}
I haven't tested myself...
scanf("%[^\n]s",arr); stops when it encounters \n
The stdin still holds \n
scanf("%[^\n]s",sb); stops when it encounters the very same \n at the end of the 1st human input
Btw it is a good practice to use the combination of fgets and sscanf instead of scanf.
"%[...]" does not need a trailing 's'.
"%[...]" does not consume leading white-space.
Whenever scanning strings, incorporate width limits.
Check scanf() return value.
char arr[50];
// v--- Space added to consume any white-space including any \n
if (scanf(" %49[^\n]", arr) != 1) Handle_Error();
char sb[20];
if (scanf(" %19[^\n]", sb) != 1) Handle_Error();
In OP's original code, OP is getting garbage because the scanf() did not work. The first "%[^\n]s" likely worked OK, but left a '\n' in stdin for the next IO operation. The 2nd "%[^\n]s" tries to scan that left-over '\n' and since it does not match "%[^\n]", scanf() stopped and put nothing in sb. So uninitialized sb had whatever garbage it started with.
Better yet, use fgets().
Replace:
scanf("%[^\n]s",arr);
...
scanf("%[^\n]s",sb);
With:
scanf("%49s %19s",arr,sb);
Use this code if you do not want to use fgets or sscanf
int main()
{
char arr[50];
int ll;
char sb[20];
printf("enter the string\n");
scanf("%[^\n]s",arr);
fflush(stdin);//to clear \n from the buffer
printf("string=%s\n",arr);
printf("\n enter sub");
scanf("%[^\n]s",sb);
printf("\n sub-string=%s",sb);
return 0;
}

Why gets does not work when I use it with scanf?

When i use gets separately this works. But, when i use scanf in my program it does not work. Can anyone explain what I've missed?
#include <stdio.h>
#include <stdlib.h>
int main(){
char a[]="computer";
char b[]={'p','c','\0'};
char c[30];
char d[30];
printf("a=%s,b=%s\n",a,b);
printf("enter a word\n");
scanf("%s",c);
printf("%s",c);
printf("enter a sentence\n");
gets (d);
printf("%s",d);
return 0;
}
gets doesn't skip the white-space characters before starting to read the string while scanf does.
After your first input, there is \n character in the buffer left behind by first scanf call. This \n is read by gets but scanf skips this white-space character.
this can be solved by using a getchar statement after the scanf call.
printf("enter a word\n");
scanf("%s",c);
getchar();
Do not use gets neither scanf (they do not check array bound), instead use fgets.
printf("enter a word\n");
fgets(c, 30, stdin);
printf("%s",c);
printf("enter a sentence\n");
fgets(d, 30, stdin);
printf("%s",d);
Scanf leaves behind "\n"(without quotes) and then gets() function reads only it.
scanf("%s",c) left the Enter or \n in stdin. When gets() executed it consumed that and returned an empty string. gets() reads in all data up to the \n and trims it off before returning.
The format specifiers like %d %s, etc. (all except %n %c %[) and the whitespace format directives like " " direct scanf() to skip leading whitespace. scanf() itself does not skip leading whitespace.
Suggest using fgets() and avoid using gets().
char buf[100];
printf("enter a word\n");
fgets(buf, sizeof buf, stdin);
sscanf(buf, "%29s", c); // 29 because c is size 30
printf("%s\n",c);
printf("enter a sentence\n");
fgets(d, sizeof d, stdin);
printf("%s",d);
scanf removes whitespace automatically from before the datum it's trying to get. An exception to this is the character formats (primarily %c), which don't remove whitespace. However, scanf leaves whitespace after the datum. Therefore, you'll need a way to get rid of that. Use
getc(stdin);
you can then continue on your merry way. This page has more documentation on getc.

Resources