Character is not accepted [duplicate] - c

This question already has answers here:
C skipping one command of a function? [duplicate]
(2 answers)
Closed 7 years ago.
I've written a C program to count the number of occurrences of an entered character. When I execute,I could only enter the file name.Before I enter the character to be counted , the next statement executes.The output I get is shown below.
Enter the file name
test.txt
Enter the character to be counted
File test.txt has 0 instances of
Here is my code
#include<stdio.h>
#include<stdlib.h>
int main()
{
FILE *fp1;
int cnt=0;
char a,ch,name[20];
printf("Enter the file name\n");
scanf("%s",name);
//fp1=fopen(name,"r");
printf("Enter the character to be counted\n");
scanf("%c",&ch);
fp1=fopen(name,"r");
while(1)
{
a=fgetc(fp1);
if (a==ch)
cnt=cnt+1;
if(a==EOF)
break;
}
fclose(fp1);
printf("File %s has %d instances of %c",name,cnt,ch);
return 0;
}
How to resolve this?

It's a common beginners problem, especially when using the scanf family of functions.
The problem is that when you enter the file-name, and press Enter, the scanf function reads the text but leaves the Enter key, the newline, in the input buffer, so when you next read a character it will read that newline.
The solution is very simple: Tell scanf to read and discard any leading white-space by putting a single space in the scanf format:
scanf(" %c",&ch);
// ^
// |
// Note leading space
If you follow the link to the scanf reference it will tell you that almost all formats automatically reads and discards leading white-space, one of the three exceptions is just the format to read single characters, "%c".

Related

How to prompt the user to enter an integer and a character from the keyboard in C [duplicate]

This question already has an answer here:
How to read / parse input in C? The FAQ
(1 answer)
Closed 4 years ago.
I am trying to figure out the best way to get an integer and a character from a user
Here is what I have so far:
#include <stdio.h>
int main()
{
int a;
char b;
printf("enter the first number: \n");
scanf("%d", &a);
printf("enter the second char: \n");
scanf("%c", &b);
printf("Number %d",a);
printf("Char %c",b);
return 0;
}
The output is not shown correctly. Is there any problem with this?
Your input and output statements are fine. Just replace printf("Number %d",a); with printf("Number %d\n",a); to better format the output. Also you should change your second scanf statement to scanf(" %c", &b);. This will deal with the newline character entered after the number is inputted.
After you enter the number, you pressed the Enter key. Since the scanf function works on the input stream, when you try to process the next char after reading the number, you are not reading the character you typed, but the '\n' character preceding that. (i.e. because the Enter key you pressed added a '\n' character to your input stream, before you typed your char)
You should change your second call to scanf with the following.
scanf(" %c", &b);
Notice the added space character in the formatting string. That initial space in the formatting string helps skip any whitespace in between.
Additionally, you may want to add \n at the end of the formatting strings of both printf calls you make, to have a better output formatting.
Here you need to take care of hidden character '\n' , by providing the space before the %c in scanf() function , so the "STDIN" buffer will get cleared and scanf will wait for new character in "STDIN" buffer .
modify this statement in your program : scanf("%c",&b); to scanf(" %c",&b);

How can I enter space bar as input using scanf? [duplicate]

This question already has answers here:
How do you allow spaces to be entered using scanf?
(11 answers)
Closed 5 years ago.
I'm writing an fuction and I got a problem, the scanf function cant read spacebar " ", how can I solve it?
void add()
{
char choose2;
FILE *fp;
struct booking book;
system("cls");
fp=fopen("hotelbooking.txt","a");
if(fp == NULL)
{
printf("There are no data file!");
}
else
{
printf("Add New Hotel Booking Record(s)\n");
printf(" Name of Traveller: \n");
scanf("%s",book.travellername);
fprintf(fp,"\n%s",book.travellername);
printf(" Destination: ");
scanf("%s",book.destination);
fprintf(fp,"\n%s",book.destination);
fclose(fp);
}
}
In the tervellername part, If I want to enter e.g. "Jason George", How can I scan the space bar between the name?
I'm using the structure below:
struct booking
{
char travellername[20];
char destination[20];
}book;
scanf() with %s format specifier stops scanning as soon as it hits a whitespace. You cannot scan space using it.
Quoting C11, chapter ยง7.21.6.2,
s Matches a sequence of non-white-space characters.
For a better and robust alternative, you can use fgets() to scan an entire line, terminated by a newline. Remember, in this case, fgets() scans and stores the terminating newline also in the supplied buffer, so you need to manually get rid of it, if that matters.
Try this
scanf("%[^\n]", book.travellername);
Input string will read space separated words and terminate upon encountering a newline character (i.e. \n). Also be Careful that this does not get buffer overflows. so define size of book.travellername accordingly.
update: I have updated the format specifier.

why %s does not print the string after it encounters a space character? [duplicate]

This question already has answers here:
How do you allow spaces to be entered using scanf?
(11 answers)
Closed 6 years ago.
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output:
Enter name: Dennis Ritchie
Your name is Dennis.
So far I haven't found any specific valid reason for this question. Can anyone help me out?
scanf only read till it gets to space that is why it is not storing after the first space , so your printf function is not faulty , it is the scanf that is not storing the complete string , stopping on encountering first space.
One should never use gets() , unless they completely know what they are doing , because it does not have buffer overflow protection , it continue to read after the buffer ends until it finds a new line or encounter a EOF. You can read more about that here.Please Check This Why is the gets function so dangerous that it should not be used?
You should instead use fgets().
#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
fgets(name,20,stdin);
printf("Your name is %s.", name);
return 0;
}
Remember fgets() also reads newline character(the one you get when you press enter) so you should manually remove that.
Also I highly Recommend this answer for using fgets() to its full potential and avoiding common pitfalls.
This answer tells about using scanf to read string.What it says is the following:
int main(){
char string[100], c;
int i;
printf("Enter the string: ");
scanf("%s", string);
i = strlen(string); // length of user input till first space
do{
scanf("%c", &c);
string[i++] = c; // reading characters after first space (including it)
}while (c != '\n'); // until user hits Enter
string[i - 1] = 0; // string terminating
return 0;
}
How this works? When user inputs characters from standard input, they will be stored in string variable until first blank space. After that, rest of entry will remain in input stream, and wait for next scanf. Next, we have a for loop that takes char by char from input stream (till \n) and appends them to end of string variable, thus forming a complete string same as user input from keyboard.

Error in C simple program [duplicate]

This question already has answers here:
C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf [duplicate]
(7 answers)
Closed 8 years ago.
This is part of a university lab and the TA tells me there is an error but I haven't a clue. When I run it it asks me for the first char but then runs through the program and doesn't ask me at the second scanf.
#include <stdio.h>
int main(void) {
char sen, ben;
printf("Type in a character: ");
scanf("%c", &sen);
printf("The key just accepted is %d", sen);
printf("\nType in another character: ");
scanf("%c", &ben);
printf("The key just accepted is %d", ben);
}
Actually this is C not C++. Save it as file.c.
Try this:
#include <stdio.h>
int main(void) {
char sen, ben;
printf("Type in a character: ");
sen = getchar();
printf("The key just accepted is %d", sen);
printf("\nType in another character: ");
getchar();
ben = getchar();
printf("The key just accepted is %d", ben);
}
Explanation: when you enter the first character and press enter it takes enter's ASCII code as the second.
I suggest not to use scanf. But it works both ways if you put a getchar to "take" the enter.
Adding a space before %c in the second scanf will solve the issue.
This is done because scanf does not consume the \n character after you enter the first character and leaves it in the stdin.As the Enter key(\n) is also a character,it gets consumed by the next scanf call.The space before the %c will discard all blanks like spaces.
When you are scanning a character(%c) using scanf,add a space before %c as it would help reduce confusion and help you. Therefore, in both the scanfs , you can add the space.
When you pressed your key and then hit enter, you typed in two keys. The first was the desired key ,a for example, and the second was the key <enter> typically written as \n. So, your second scanf captures the result \n.
Since printing out the \n character doesn't result in something that is easy to see on the screen, it will appear like your program is just skipping the second scanf and printing out only the fixed parts of the printf without a easily viewable value.
One way to get around this problem is to consume all the key strokes just before the key you want to capture. This is done by accepting more input after the character up until you see a newline character \n. Once you see that character, then you do your next read.
// flush extra input up the to carriage return
char flush = 0;
while (flush != '\n') {
scanf("%c", &flush);
}
// now read my desired input
scanf("%c", &ben);
that's because nobody accepts '\n'. call scanf like this scanf("%c%*c", &sen). %*c means you want to omit one character, which is '\n'.
btw, void main() is allowed. main function is not the real entry point of executable, so it's ok to do that. but it seems not everybody likes it.

Odd loop does not work using %c [duplicate]

This question already has answers here:
C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf [duplicate]
(7 answers)
Closed 8 years ago.
I am leaning C programming. I have written an odd loop but doesn't work while I use %c in scanf().Here is the code:
#include<stdio.h>
void main()
{
char another='y';
int num;
while ( another =='y')
{
printf("Enter a number:\t");
scanf("%d", &num);
printf("Sqare of %d is : %d", num, num * num);
printf("\nWant to enter another number? y/n");
scanf("%c", &another);
}
}
But if I use %s in this code, for example scanf("%s", &another);, then it works fine.Why does this happen? Any idea?
The %c conversion reads the next single character from input, regardless of what it is. In this case, you've previously read a number using %d. You had to hit the enter key for that number to be read, but you haven't done anything to read the new-line from the input stream. Therefore, when you do the %c conversion, it reads that new-line from the input stream (without waiting for you to actually enter anything, since there's already input waiting to be read).
When you use %s, it skips across any leading white-space to get some character other than white-space. It treats a new-line as white-space, so it implicitly skips across that waiting new-line. Since there's (presumably) nothing else waiting to be read, it proceeds to wait for you to enter something, as you apparently desire.
If you want to use %c for the conversion, you could precede it with a space in the format string, which will also skip across any white-space in the stream.
The ENTER key is lying in the stdin stream, after you enter a number for first scanf %d. This key gets captured by the scanf %c line.
use scanf("%1s",char_array); another=char_array[0];.
use getch() instead of scanf() in this case. Because scanf() expects '\n' but you are accepting only one char at that scanf(). so '\n' given to next scanf() causing confusion.
#include<stdio.h>
void main()
{
char another='y';
int num;
while ( another =='y')
{
printf("Enter a number:\t");
scanf("%d", &num);
printf("Sqare of %d is : %d", num, num * num);
printf("\nWant to enter another number? y/n");
getchar();
scanf("%c", &another);
}
}

Resources