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.
Related
#include<stdio.h>
int main(){
char arr[20];
int a;
int count=0;
while(1){
printf("enter string with space:");
fflush(stdin);
scanf("%[^\n]%*c", arr);
printf("enter integer:");
scanf("%d",&a);
count++;
if(count==4){
break;
}
}
}
I want to read string with space and I have to use this code. I wrote this in while loop and I want to read string and after integer number and it does not work.
Output:
enter string with space:hey hey
enter integer:159
enter string with space:enter integer:
But output should be:
enter string with space:hey hey
enter integer:159
enter string with space:.... heyy
enter integer: 1235
fflush() is not defined input streams such as stdin. You will find that it works on Microsoft's C library, but not GNU.
Your scanf() call is incorrect. The first format specifier is incorrect, and you have no format specifier for string ;
scanf("%*[^\n]%*c") ;
will discard any remaining buffered characters to the end of the line inclusive. It accepts no input - it is not clear what string is or what you want to do with it. I'd suggest using a separate input call for that, for clarity.
Another somewhat less arcane solution is:
int c ;
while ((c = getchar()) != '\n' && c != EOF) { }
enter string with space:enter integer:
This happens because after you enter integer input, \n is still left in the stream. %[ does not skip leading whitespace unlike most other format specifiers. Change scanf("%[^\n]%*c", arr); to scanf(" %[^\n]%*c", arr); so it manually skips the leading whitespace before taking input.
As for fflush(stdin), that is undefined behavior (see Using fflush(stdin)). #Clifford already provides two nice solutions to that issue.
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".
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;
}
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.
what is the problem here? scanf doesnt seems to working in while loop. i was trying to find out vowel & consonent until user wants.
Here's the code:
#include <stdio.h>
main()
{
char x,c;
do
{
printf("enter\n");
scanf("%c",&x);
if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u')
printf("vowel\n");
else
printf("consonent\n");
printf("do u want to continue ?(y/n)\n");
scanf("%d",&c);
if(c=='n')
printf("thnks\n");
} while(c=='y');
return 0;
}
You are trying to read a character using %d which is wrong. Use %c instead.
Change code to scanf("%c",&c) your original code is getting the y/n entries as digits not characters
Edit:
Probably you are getting the carage return instead of the character try using getc or fgets instead and get the first character.
I think the problem might be here:
scanf("%d",&c);
It should be:
scanf("%c",&c);
Here is the Correct code:
#include <stdio.h>
int main()
{
char x,c;
do
{
printf("enter\n");
scanf("%c",&x);
getchar(); //to remove the \n from the buffer
if(x=='a'||x=='e'||x=='i'||x=='o'||x=='u')
printf("vowel\n");
else
printf("consonent\n");
printf("do u want to continue ?(y/n)\n");
scanf("%c",&c); //Here you were using %d instead of %c
getchar(); //to remove the \n from the buffer
if(c=='n')
printf("thnks\n");
}while(c=='y');
return 0;
}
Both scanfs should be changed like this:
scanf(" %c",&x);
...
scanf(" %c",&c);
Note the space before the %, it's important: it consumes leading whitespace, which includes the endline characters left over in stdin after processing the input.
Please try with this code to run the loop multiple times.
EDIT: Different solution without fflush(stdin). Please define a string of 8 characters as
char str[8];
and modify the code in the loop as
fgets(str, 8, stdin); // To read the newline character
printf("do u want to continue ?(y/n)\n");
scanf("%c",&c);
fgets(str, 8, stdin); // To read the newline character