This question already has answers here:
i want to getchar twice but i cant
(2 answers)
Closed 7 years ago.
I have been tasked to create a simple lower to upper case program. However, while testing if my input prints correctly, I have noticed that every time I enter a character, it always loops again even when its not supposed to.
#include <stdio.h>
int main() {
char input;
//enter a character
//set the given input char to variable
printf("Enter a character in lower case: \n");
input = getchar();
//Sentinel value is Q
while (input != 'Q'){
printf("you entered %c.\n",input);
printf("\n");
printf("Enter a character in lower case: \n");
input = getchar(); //gets input from inside the loop
}
printf("Goodbye \n");
return 0;
}
test output (I input the character 'g' and pressed enter once):
Enter a character in lower case:
g
you entered g.
Enter a character in lower case:
you entered
.
I'm not seeing the problem.
The problem here is caused by the newline character entred into the stdin by pressing the ENTER key. Before proceeding for the next input, you need to clear the input buffer , like adding
while (getchar() != '\n');
before asking for the next input.
That said, getchar() returns an int. A char may not be enough to hold the return value always, Change
char input;
to
int input = 0;
Related
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.
This question already has answers here:
i want to getchar twice but i cant
(2 answers)
Closed 7 years ago.
I have been tasked to create a simple lower to upper case program. However, while testing if my input prints correctly, I have noticed that every time I enter a character, it always loops again even when its not supposed to.
#include <stdio.h>
int main() {
char input;
//enter a character
//set the given input char to variable
printf("Enter a character in lower case: \n");
input = getchar();
//Sentinel value is Q
while (input != 'Q'){
printf("you entered %c.\n",input);
printf("\n");
printf("Enter a character in lower case: \n");
input = getchar(); //gets input from inside the loop
}
printf("Goodbye \n");
return 0;
}
test output (I input the character 'g' and pressed enter once):
Enter a character in lower case:
g
you entered g.
Enter a character in lower case:
you entered
.
I'm not seeing the problem.
The problem here is caused by the newline character entred into the stdin by pressing the ENTER key. Before proceeding for the next input, you need to clear the input buffer , like adding
while (getchar() != '\n');
before asking for the next input.
That said, getchar() returns an int. A char may not be enough to hold the return value always, Change
char input;
to
int input = 0;
This question already has answers here:
Why does scanf appear to skip input?
(7 answers)
Closed 8 years ago.
Here i have a simplified piece of code that asks and displays a number on a loop, it works fine for all numbers i type in, But if i input a letter or a special character (!"£$%^&*-_=+ etc ) it goes mental and skips the input.
#include<stdio.h>
int number;
int main()
{
do
{
system("cls");
printf("Enter a number");
scanf("%d",&number);
}
while(1==1);
}
My question is, what can i do to stop this from happening?, is there some code that filters out this nonsense or is scanf pretty much worthless?
//Edit: This is somehow been marked as a duplicate, heh.
From here:
if the input doesn't conform to the expected format scanf() can be
impossible to recover sensibly [..] A "better" alternative here is to
use an input function like fgets() or fgetc() to read chunks of input,
then scan it with sscanf() or parse it with string handling functions
like strchr() and strtol().
scanf with %d will fail to scan an integer and returns 0 when a character was entered. So just check if it doesn't return 1. If it doesn't , a character was entered (if it returned 0) or else, an integer was entered. Note that if EOF was encountered, scanf will return -1.
if(scanf("%d", &number) != 1)//character entered
{
printf("Invalid input\n");
scanf("%*s");//clear the invalid character(s) from stdin
}
else
{
//a number was entered
}
The reason that scanf becomes "mental" and the program prints Enter a number many times when you enter a character is that when the scanf fails to scan an integer from the standard input stream(stdin), it returns 0 and the execution continues. When scanf is called the next time, it sees the characters which you had entered the last time and again fails and this process continues. To prevent it, just clear the stdin like I've done in the code above.
Another popular way of clearing the stdin is using:
int c;
while((c = getchar()) != '\n' && c != EOF);
This question already has answers here:
Scanf skips every other while loop in C
(10 answers)
Closed 5 years ago.
program to count number of +ve, -ve and zeroes in the input.the printf statement in the for loop is executed more than once.how to correct this code.the count is correct but output is not in the expected format.
#include<stdio.h>
main()
{
int n,pc,nc,zc;
char s;
pc=nc=zc=0;
for(;1;) {
printf("do you wanna enter: y/n\n");
s=getchar();
if(s=='y') {
printf("enter num:\n");
scanf("%d",&n);
if(n>0) {
pc+=1;
}
if(n<0) {
nc+=1;
}
if(n==0) zc+=1;
}
if(s=='n') break;
}
printf("No.of +ve num: %d \n",pc);
printf("No.of -ve num: %d \n",nc);
printf("No.of zeroes: %d \n",zc);
}
output:
xplorer#kali:~/Desktop/docs/yk/chap3$ ./a.out
do you wanna enter: y/n
y
enter num:
4
do you wanna enter: y/n
do you wanna enter: y/n
y
enter num:
8
do you wanna enter: y/n
do you wanna enter: y/n
y
enter num:
-7
do you wanna enter: y/n
do you wanna enter: y/n
n
No.of +ve num: 2
No.of -ve num: 1
No.of zeroes: 0
\n is left behind in input buffer by previous call of getchar because it reads a character at a time. As '\n' is also a character, n next iteration getchar reads that left over \n .
You need to flush the input buffer:
int c;
while((c = getchar()) != '\n' && c != EOF);
...
{
printf("enter num:\n");
scanf("%d",&n);
...
The 'scanf' in the above snippet of the question code reads an integer from stdin, but only after the user presses return. The return character '\n' is also sent to stdin, however, the above 'scanf' is satisfied with reading only the integer value, and leaves the '\n' character in the stdin stream. The next time any function attempts to read from stdin, the '\n' character will be there to read. This is causing undesirable results in the question code here:
...
{
printf("do you wanna enter: y/n\n");
s=getchar();
....
The 'getchar' function read the '\n' character from stdin, and the program acts on it.
One way to avoid this problem is to have the 'scanf' function read the residual '\n' character from the buffer. This can be done by changing this:
scanf("%d",&n);
To this:
scanf("%d%*c",&n);
The latter reads the integer value from the stdin stream, and then reads (and discards) the residual '\n' character.
After each read from stdin, remove all additional characters from the buffer with:
/* discard (flush) remaining chars in stdin */
while (ch !='\n') ch = getchar();
As discussed in other answers, after you test with scanf or other input utilities, additional characters remain in the input buffer. You cannot reliably flush the input buffer with any standard function such as fflush as they apply to output buffers and not to input buffers. The simple while loop that scans for the newline insures that all characters are read regardless of whether a carriage return is present before the newline and is therefore portable between most OS's.
If curses.h is available on your system, You can use flushinp function to flush the input.
Check C FAQ: http://c-faq.com/stdio/stdinflush2.html
You have only checked for two conditions i.e 'y' or 'n' and not for the other so It might happen that it takes input other than 'y' or 'n'from previous inputs and loop continues. So just chk by printing if it is taking any other input and make changes accordingly.
Replace s=getchar(); with
do
{
s=getchar();
}while (isspace(s));
Things will start working.
My program which finds prime factors is all set...the only thing left that I need to do is this type of output:
Do you want to try another number? Say Y(es) or N(o): y
//asks for another number (goes through the program again)
Do you want to try another number? Say Y(es) or N(o): n
//Thank you for using my program. Good Bye!
I have my attempt at this below...When I type n it does the correct output. But if I type 'y' it just says the same thing n does....How can I loop the entire program without putting the code for the program inside this while loop I have? So when I press y it goes through the program again?
int main() {
unsigned num;
char response;
do{
printf("Please enter a positive integer greater than 1 and less than 2000: ");
scanf("%d", &num);
if (num > 1 && num < 2000){
printf("The distinctive prime facters are given below: \n");
printDistinctPrimeFactors(num);
printf("All of the prime factors are given below: \n");
printPrimeFactors(num);
}
else{
printf("Sorry that number does not fall within the given range. \n");
}
printf("Do you want to try another number? Say Y(es) or N(o): \n");
response = getchar();
getchar();
}
while(response == 'Y' || response == 'y');
printf("Thank you for using my program. Goodbye!");
return 0;
} /* main() */
The problem is probably, that you're getting something that isn't y from getchar and the loop exits, as the condition is not matched.
getchar() may use a buffer, so when you type 'y' and hit enter, you will get char 121 (y) and 10 (enter).
Try the following progam and see what output you get:
#include <stdio.h>
int main(void) {
char c = 0;
while((c=getchar())) {
printf("%d\n", c);
}
return 0;
}
You will see something like this:
$ ./getchar
f<hit enter>
102
10
What you can see is that the keyboard input is buffered and with the next run of getchar() you get the buffered newline.
EDIT: My description is only partially correct in terms of your problem. You use scanf to read the number you're testing against. So you do: number, enter, y, enter.
scanf reads the number, leaves the newline from your enter in the buffer, the response = getchar(); reads the newline and stores the newline in response, the next call to getchar() (to strip the newline I described above) gets the 'y' and your loop exits.
You can fix this by having scanf read the newline, so it doesn't linger in the buffer: scanf("%d\n", &number);.
When reading input using scanf (when you enter your number above), the input is read after the return key is pressed but the newline generated by the return key is not consumed by scanf.
That means your first call to getchar() will return the newline (still sitting in the buffer), which is not a 'Y'.
If you reverse your two calls to getchar() - where the second one is the one you assign to your variable, your program will work.
printf("Do you want to try another number? Say Y(es) or N(o): \n");
getchar(); // the newline not consumed by the scanf way above
response = getchar();
just put getchar() after scanf statement of yours that will eat the unnecessary '\n' from buffer...
As others have stated, there is a single '\n' character in the input stream left over from your earlier call to scanf().
Fortunately, the standard library function fpurge(FILE *stream) erases any input or output buffered in the given stream. When placed anywhere between your calls to scanf() and getchar(), the following will rid stdin of anything left in the buffer:
fpurge(stdin);