How to ignore an empty line from the keyboard in C - c

I'm struggling with what seems a trivial problem in C inputting data from the keyboard, but I'm a C noob (with some background in Java, though)
What I need: I need to type an int value from the keyboard (then press Enter), then I need the user to press Enter only without inputting anything, and then to type another int (and press Enter one more time).
What I can do:
int a = 0;
int b = 0;
scanf("%d", &a);
skip_line_cool_function();
scanf("%d", &b);
printf("You have just entered: &d and &d", a, b);
As you can see, I don't know how to skip the line.
What I have tried: scanf entering a dummy C-string, but, as you know, when you enter nothing, it patiently waits for at least something to be entered.
What I Googled: I suspect that fgets can do the job, but honestly, I didn't understand how to use it in my case.

/* Read first integer */
do {
if(!fgets(buffer, sizeof buffer, stdin)) break;
} while( last_character_of(buffer) != '\n');
/* Read next integer */

If you are this much rigid about the UI that the user will only press a single enter then why not do this?
int a = 0;
int b = 0;
scanf("%d", &a);
getchar(); /* this will get the enter pressed after entering a */
getchar(); /* this will get the enter for the blank line */
scanf("%d", &b);
printf("You have just entered: &d and &b", a, b);
Also the code snippet you've posted will result into compile error. printf() will need integer format specifier %d to work properly. Use this:
printf("You have just entered: %d and %d", a, b);

Related

C program, getting the integer value of a character. Why everything comes out after line 10?

Hi I am new to programming and I got a trouble when I try to make a little change to the example in the book.
/* Chapter 3 Example, C Prime Plus */
#include <stdio.h>
int main(void)
{
char Letter, ch;
int intValue;
printf("Please enter a letter: \n");
scanf("%c", &Letter); /* user inputs character */
printf("The code for %c is %d.\n", Letter, Letter);
printf("Now is another we to implement the process: \n");
printf("RN, the value of ch is %c, and the value of intValue is %d\n", ch, intValue);
printf("Please enter a letter: \n");
scanf("%c", &ch);
intValue = ch;
printf("The code for %c is %d.\n", ch, intValue);
return 0;
}
When I run it, the outcome would be
Please enter a letter:
M
The code for M is 77.
Now is another we to implement the process:
RN, the value of ch is , and the value of intValue is 0
Please enter a letter:
The code for
is 10.
and the part
"
Now is another we to implement the process:
RN, the value of ch is , and the value of intValue is 0
Please enter a letter:
The code for
is 10. " will all come out without asking me to enter a value.
I want to know why and are there any other way to implement it that is different from examples in the book?
Thank you for your time!
Hi Matt_C and welcome to SO.
First, you don't need the second bloc of printfs and the scanf, it just trying to do the same thing and there is an order error.
Second, it is tricky when you try consecutive scanf, it holds the last key pressed (enter is the last key pressed = \n). This is why it skips the second scanf.
There a little solution for that, add a space at the beginning of the scanfs. Try this:
int main() {
char exit, letter;
while (1) {
printf("Please enter a letter: ");
scanf(" %c", &letter);
printf("\nThe code for '%c' is %d. \n\n", letter, letter);
printf("Exit ? (y/n): ");
scanf(" %c", &exit);
if(exit == 'y')
{
break;
}
system("clear"); // UNIX
//system("cls"); // DOS
}
}
Don't forget to choose one answer that you believe is the best solution to your problem.

Why c programme code is not asking the second value & how come char is stored in int form I took this from an example on web

#include <stdio.h>
// source tutorial points
int main(){
int c;
char d;
printf("Enter First value \n");
c = getchar();
printf("Enter Second value \n");
d = getchar();
printf("You have entered first \n");
putchar(c);
printf("You have entered second \n");
putchar(d);
return(0);
}
when I am entering first value it is not asking for other value please help I do not expect a character not possible in char.
Because each time you input a character and hit ENTER. So, second getchar in your code reads the enter character.
Your code should change to:
c = getchar();
getchar(); // for consuming the enter character
printf("Enter Second value \n");
d = getchar();
getchar(); // for consuming the enter character
The output:
Enter First value
a
Enter Second value
b
You have entered first
a
You have entered second
b

getchar() doesnt wait for enter press [duplicate]

This question already has answers here:
getchar does not stop when using scanf
(5 answers)
Closed 3 years ago.
I started C just a while ago (same as coding), so I`m a noob.
My Goal:
to state that the user hasn't entered a or b and then wait for the user to press enter to return to the calculator menu.
My problem:
getchar() doesn't wait for me to press enter. (Case 3)
#include <stdlib.h>
int main()
{
for (int i = 0;i == 0;){
int options=0,enteredA=0, enteredB=0;
float *a, A, *b, B, *c, C;
a=&A,b=&B,c=&C;
printf ("Calculator\nAvailable options:\n[1]Enter value for A\n[2]Enter value for B\n[3]Addition\n[9]Exit\n");
scanf ("%d",&options);
system ("clear");
switch (options) {
case 1:
printf("Enter a value for A:");
scanf ("%f",&*a);
enteredA++;
break;
case 2:
printf("Enter a value for B:");
scanf ("%f",&*b);
enteredB++;
break;
case 3:
if ((enteredA==0) | (enteredB== 0)){
printf("A and B are not initialized yet. Please enter a value in the menu.\nPress [Enter] to continue to the menu:\n");
fflush(stdin);
getchar();
break;
} else{
printf("%f+%f=%f\n",*a,*b,*c=*a+*b);
fflush(stdin);
getchar();
break;
}
break;
case 9:i++;break;
}
system("clear");
}
printf("Calculator Shut Down");
return 0;
}
In the following line:
scanf ("%d",&options);
you actually enter a number, and a newline character. The scanf function reads only the number. It leaves the newline (\n) in the input stream.
When you call getchar(), it will find a newline in the input stream. Hence, it will read it without waiting for user input. It only wait for user input if it didn't find anything in the input stream.
A possible workaround for this is to call getchar two times instead of one.
The first call will read the already existing newline in the stream. The second call won't find anything in the input stream. So, it will wait for user input as you expect.
I have some small comments that aren't related to your question:
You use scanf ("%f",&*a);. Why not just scanf("%f", a); or scanf("%f", &A); ?
Why you even create a pointer a for the variable A ?
I don't think you really need the variable c as well.
You don't need the variable i in the loop as well.
At the beginning of the loop, you keep re-initializing enteredA and enteredB variables to zero. That way, the condition in case 3: will be always true. You need to move these variables outside of the loop.
Your code also missing a #include <stdio.h>.
I'd simplify things like the following:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int enteredA = 0, enteredB = 0;
while (1)
{
int options;
float A, B;
printf ("Calculator\nAvailable options:\n[1]Enter value for A\n[2]Enter value for B\n[3]Addition\n[9]Exit\n");
scanf("%d", &options);
getchar(); // The extra getchar to read the newline left in the stdin.
system ("clear");
switch (options)
{
case 1:
printf("Enter a value for A:");
scanf("%f", &A);
enteredA++;
break;
case 2:
printf("Enter a value for B:");
scanf ("%f", &B);
enteredB++;
break;
case 3:
if (enteredA ==0 || enteredB == 0)
{
printf("A and B are not initialized yet. Please enter a value in the menu.\nPress [Enter] to continue to the menu:\n");
}
else
{
printf("%f + %f = %f\n", A, B, A + B);
}
getchar();
break;
case 9:
printf("Calculator Shut Down");
return 0;
}
system("clear");
}
}

C Program - Basic Calculator

I'm trying to write a basic calculator program in C, and I'm almost there! I have one issue though, and it's concerning repeatedly querying the user for input.
I can get through my loop once, but even though the user inputs the correct character, my program still breaks out of the loop.
I'm fairly new to C, but I've done a decent amount of programming in Java, so I understand the functionality of loops, conditionals, and data types.
#include <stdio.h>
int main()
{
char yes;
int a, b, c, choice;
yes = 'y';
while(yes == 'y' || yes == 'Y')
{
printf("Enter first integer: ");
scanf("%d", &a);
printf("Enter second integer: ");
scanf("%d", &b);
printf("\nAdd(1), Subtract(2), Multiply(3), Divide(4): ");
scanf("%d", &choice);
printf("\n");
switch(choice)
{
case(1):
c = a + b;
printf("%d + %d = %d\n", a, b, c);
break;
case(2):
c = a - b;
printf("%d - %d = %d\n", a, b, c);
break;
case(3):
c = a * b;
printf("%d * %d = %d\n", a, b, c);
break;
case(4):
c = a / (float)b;
printf("%d / %d = %d\n", a, b, c);
break;
default:
printf("Incorrect choice. Try again.\n");
}
printf("\nAgain (Y/N): ");
scanf("%c", &yes);
}
return 0;
}
You need to consume the trailling newline, enter remains in the stdin buffer ready to be read by the next scanf.
Change
scanf("%c", &yes);
to
scanf(" %c", &yes);
The problem is that the newline character is left on the input after inputting a number to choose what operation to do. So when the user is asked if they want to do it again, the newline is taken instead of the y or n. I might be wrong, it's been a while since I've done some programming.
What worked for me to fix it was to put a little bit of code after the line
printf("\nAgain (Y/N): ");
Adding this bit right after the printf statement will remove the newline from the input and should do the trick.
while(getchar() != '\n')
getchar();
Maybe someone else can explain exactly why this works, I don't remember the specifics. It's a little thing that I found useful to remember, it comes up every now and again.

Why is scanf grabbing \n?

I'm writing a basic C program that will convert either Celsius or Fahrenheit to the other.
I have a scanf statement where the user enters the temperature they want to convert, and then a printf statement asking for whether that temperature was in c or f.
when I compile, the scanf asking for char c or f is instead grabbing the \n from the previous scanf. according to my debugger.
the code looks like this:
int celcius(void){
double originalTemp = 0;
double newTemp;
char format;
printf ("enter a temperature: ");
scanf ("%lf",&originalTemp); //what is the original temp?
printf ("enter c if in celcius, enter f if in ferenheit: "); //enter c or f
scanf("%c", &format); //why do I need to do this twice??, this one grabs \n
scanf("%c", &format); //this one will pick up c or f
if (format == 'c'){
newTemp = originalTemp*1.8+32;
printf("%.2lf degrees Farenheit\n", newTemp);
} //convert the Celcius to Ferenheit
else if (format == 'f'){
newTemp = (originalTemp-32)/1.8;
printf("%.2lf degrees Celcius\n", newTemp);
} //convert the Ferenheit to Celcuis
else {
printf ("ERROR try again.\n");
} //error if it isn't f or c
return 0;
}
am I missing something? I know thatscanf looks in the input stream for the next char in this case, but why is \n still in the input stream at this point?
and is there a "proper" way to fix this other than get char?
Space in the format string matches whitespace, so you can just match away/skip the cr/lf;
printf ("enter c if in celcius, enter f if in ferenheit: "); //enter c or f
scanf(" %c", &format); // get next non white space character, note the space
if (format == 'c'){
The rule is to write a getchar() after every integer/float/double input if you take char/string inputs later. This getchar() flushes out the \n from the input buffer which is leftover by taking the integer/float/double input.
So just write a getchar(); after scanf ("%lf",&originalTemp); and you'll be fine.

Resources