This question already has answers here:
C programming: character in scanf [duplicate]
(2 answers)
Closed 8 years ago.
I have the following code, i wanted to terminate the while loop if any key except 1 & 2 is press. but only do executes once. and not while. why my while condition is always false. please guide:
char a;
do
{
printf("To Enter the Employee sales press 1 \n");
printf("To Add more items press 2 \n ");
printf("Press any key to Terminate \n\n");
scanf("%c", &a);
if ( a == '1' )
{
printf("1 is presed ");
}
else if(a == '2')
{
int c;
printf("entre Value:");
scanf("%d",&c);
printf("\n");
addItem( &myArray, &size, c );
printitems(myArray, size);
}
}while(a == '1' || a == '2');
Edit So sorry, it was in single qout. i forgot to put the latest code. Even with qoutes it does not run while.
You need a space before your %c in scanf():
scanf(" %c", &a);
You're reading the first character that's entered and leaving one on the buffer. So if you enter:
'1' you're really getting two characters, first '1' then a '\n' (a "1" then a new line character, that happens when you hit enter). So it first stores '1' into a, then the second time it will read the remaining newline character into a, (it will apear to "skip" asking you for input). Since '\n' is not equal to '1' or '2' so it correctly exits.
Adding the space before the %c tells scanf() to ignore any white space left on the buffer (and new line characters count as white space)
You have declared 'a' as type char. and your while condition is
while(a == 1 || a == 2);
It should be
while(a == '1' || a == '2');
Related
int main (int argc, char *argv [])
{
char a = 'v';
for (int i = 0; a != 'x'; )
{
printf("Enter 'a' : ");
scanf("%c",&a);
}
return 0;
}
I ran it and gave input k. When I hit enter after this , why my printf runs 2 times when loop runs second times?
To understand this behaviour, we can simulate step-by-step the execution.
printf("Enter 'a' : ");
scanf("%c",&a); // User type in example 'a' and presses enter.
scanf "bufferize" a\n and places in a the value 'a'
The loop condition isn't satisfied, since 'a' == 'x' is false
printf("Enter 'a' : ");
scanf("%c",&a); // The buffer still contains `'\n'`
Since the buffer still contains unconsumed data, the next character ('\n') is placed in a and the loop continues.
The loop condition isn't satisfied, since '\n' == 'x' is false
printf("Enter 'a' : ");
scanf("%c",&a); // The buffer is empty now.
This gives you the illusion that the loop displays twice the printf, but in fact, the scanf kept reading the buffer without the need of user input.
If you enter more characters, in example qwerty, "Enter 'a' : " will be displayed 7 times, because "qwerty" contains 6 characters + '\n'
Note that using while (a != 'x') would suit better your needs than for (int i = 0; a != 'x'; )
When you use scanf and %c, it reads any character -- including the newline character you get when you press the ENTER key.
So if you run the program and type
a <Return>
you take two trips through the loop: one to read the 'a' and one to read the '\n'. If you type
<Space> <Space> a <Return>
it makes four trips through the loop. And if you type
x <Return>
it only makes one trip through the loop, because it notices you typed the 'x', and exits.
Things will become a little more clear if you print out each character you receive:
for (int i = 0; a != 'x'; )
{
printf("Enter 'a' : ");
scanf("%c",&a);
printf("you typed %d = %c\n", a, a);
}
When you see it printing
you typed 10 =
that's one of the newlines. (The value of '\n' is 10 in ASCII.)
I said that %c reads any character -- but that's somewhat unusual. Most of scanf's other format specifiers -- %d, %f, %s, etc. -- skip over "whitespace" -- that is, spaces, tabs, newlines, and a few others. But %c does not skip over those, because its job is to read exactly one character, and someone thought you might want to use it to read whitespace characters, too.
For starters this loop
for (int i = 0; a != 'x'; )
does not make sense at least because the variable i is not used within the loop.
Also this prompt
printf("Enter 'a' : ");
only confuses users. You are asking the user to enter the character 'a' while the loop stops when the character 'x' is entered.
This call of scanf
scanf("%c",&a);
reads all characters including white-space characters. It is the reason why the loop iterates one more. You have to write
scanf( " %c", &c );
^^^
In this case white spaces will be skipped.
From the C Standard (7.21.6.2 The fscanf function)
5 A directive composed of white-space character(s) is executed by
reading input up to the first non-white-space character (which remains
unread), or until no more characters can be read
The program can look the following way
#include <stdio.h>
int main(void)
{
char c;
do
{
printf( "Enter a character ('x' - exit): " );
} while ( scanf( " %c", &c ) == 1 && c != 'x' );
return 0;
}
This question already has answers here:
What is the effect of trailing white space in a scanf() format string?
(4 answers)
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 4 years ago.
I wrote this code for a school project and I have the following problem.
When I choose 1 at the first time, my program runs fine but as I choose w or r the second time, something goes wrong. None of the 2 ifs is running. I printed usr_ans2 to see the result of scanf and usr_ans2 variable is a weird question mark in a box and not a w or r character as I typed. Also I tried scanf(" %c", usr_ans2) . The question marks do not appear but the if commands are still not running.
int main(){
int usr_ans1;
char usr_ans2;
while(1){
printf("\nSelect action: (1-3)\n");
scanf("%d", &usr_ans1);
if(usr_ans1 == 1){
printf("Select to write or read from a file the text: (w/r) ");
usr_ans2 = scanf("%c", &usr_ans2);
if(usr_ans2 == 'w')
printf("You selected to write");
else if(usr_ans2 == 'r')
printf("You selected to read");
}
else if(usr_ans1 == 2){
printf("Example1");
}
else if(usr_ans1 == 3){
printf("Example2");
}
return 0;
}
scanf() in usr_ans2 = scanf("%c", &usr_ans2); will return 1 (the numbers of successfully converted specifiers) or EOF (some negative value like -1 when end-of-file or error occurs). if(usr_ans2 == 'w') will never be true.
Try
// usr_ans2 = scanf("%c", &usr_ans2);
scanf(" %c", &usr_ans2); // add the space too to skip leading white-space
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:
Problems with C scanf("%c") function to read characters one by one
(4 answers)
Closed 6 years ago.
I am writing some code and I have a prompt in the program driven by a while loop where you make a choice. However, it prints the prompt twice every time it goes through the loop and I just can't figure it out.
while (choice != 'x');
{
printf("\nChoice (a)dd (v)iew e(X)it [ ]\b\b");
scanf("%c",&choice);
if (choice == 'a') add_record();
if (choice == 'v') view_record();
}
The printf line is the one that prints twice. Thanks in advance for any help.
When you enter a character (i.e. type 'a' and press 'Enter'), the newline character ('\n') is also being read in from stdin. You can add a leading space to the format specifier to avoid this:
scanf(" %c", &choice);
The space indicates to scanf to ignore whitespace characters (such as '\n').
There are few things to notice in the question posted.
The outer while loop behavior depends on the variables initialization at first then the values being entered subsequently.
It then manipulates into print the prompt to enter choice, repeatedly (not just twice) depending on how many characters entered as input before 'enter' key is pressed.
The char i/o driver buffers the input entered and each of the characters entered is read by scarf() one at a time in this case, from the buffer. So it is needed to rewrite the code to work as following (expected from my understanding)
char choice = '!', ws = ' ';
int attempts = 0;
while (choice != 'x')
{
printf("\nAttempt:%d Choice (a)dd (v)iew e(X)it [ ]\b\b", ++attempts);
// Eat up the '\n', if one exist and Wait for valid input
while ((scanf("%c", &choice) > 0) && (choice == '\n'));
// Eat up all white space and other chars entered so far, except the last '\n'
while ((scanf("%c", &ws) > 0) && (ws != '\n'));
if (choice == 'a') add_record();
if (choice == 'v') view_record();
}
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;