scanf before printf - C - c

So, I have a printf, that asks for the users middle initial, then I have a scanf under that, then I output the users middle initial. My problem is that my printf is displaying after my scanf
C Code
#include <stdio.h>
#include <string.h>
int main(void) {
char middleInitial;
printf("What is your middle initial? ");
scanf(" %c", &middleInitial);
printf("Middle initial %c", middleInitial);
}
So as you can see, there are two printf's. My scanf is running before my first printf displays the question.
Example (This is what I'm getting in my terminal)
$ ./a.exe
c
What is your middle initial? Middle initial c
What I want
$ ./a.exe
What is your middle initial? c
Middle initial c
By the way, the c is what the user inputs

Call fflush(stdout) before your call to scanf().

type fflush(stdout); just before your first scanf() should be after first printf()
In my windows pc I face the same issue. If you use different operating system you might not need it.

Related

I'm encountering a problem while executing 3 printf() statements [duplicate]

This question already has answers here:
scanf() leaves the newline character in the buffer
(7 answers)
Closed 6 months ago.
#include <stdio.h>
int main() {
char v1,v2,v3;
printf("enter: ");
scanf("%c",&v1);
printf("enter: ");
scanf("%c",&v2);
printf("enter: ");
scanf("%c",&v3);
}
this is my sample code and I expect an output like:
enter: a
enter: b
enter: c
but I'm getting output like:
enter: a
enter: enter:
2nd and 3rd print statements are getting executed simultaneously.
The problem is that you're reading characters, so if what you enter is actually aEnterbEntercEnter, that is actually SIX characters, and what you read will be the first 3 (the a, the Enter, and the b)
What you can do is use a space in the scanf format to skip whitespace. If you use scanf(" %c", &v1); then any whitespace (such as Enter) will be skipped, which will cause your result to be what you expect. However, if someone enters something like spaceEnter, the program will seem to hang, waiting for non-whitespace to be entered
The problem lies in buffering. Read this question, which was already mentioned in the comments.
TL,DR: Use scanf(" %c", &v); to read chars, since it ignores all whitespace from the buffer, as well as the trailing newline.
Hello what I would recommend is using a library that allows you to use a function called get_char.
I wrote a program using this function that does what you wanted yours to do.
#include <stdio.h>
#include <string.h>
#include <cs50.h>
int main(void)
{
char v1 = get_char("enter: ");
char v2 = get_char("enter: ");
char v3 = get_char("enter: ");
}
So the program stores 3 char values as they are entered one after another, without all executing at once. I don't know if this is the type of answer that you are looking for or if it will help you, but I figured I would put this out there. If its not really what your looking for let me know!
This is what the terminal looks like btw.:
$ make help
$ ./help
enter: a
enter: b
enter: c

scanf is causing my code to run on forever

I was trying to use scanf but when I run the code the code goes on forever. And when I stop the code I get
[Done] exited with code=1 in 28.291 second
My question is what am I doing wrong? Here is the code I was trying to execute. My editor is VS code 1.21.0.
#include <stdio.h>
#include <string.h>
int main(){
char midInitial;
printf("What is your middle initial? ");
scanf(" %c", &midInitial);
printf("Middle inital &c ", midInitial);
}
The code does not run forever, it is waiting for the user to complete the input. Standard input is line buffered, so the user must type enter after the character for scanf() to process it. It will skip any white space characters, store the first non white space character into midInitial and return 1.
Another possible explanation is the environment you use does not support console input. Run your program from shell interpreter window in Windows.
There is another problem: the format "Middle inital &c " is incorrect, use % for conversion specifiers.
Here is a corrected version:
#include <stdio.h>
int main() {
char midInitial;
printf("What is your middle initial? ");
if (scanf(" %c", &midInitial) == 1) {
printf("Middle initial: %c\n", midInitial);
}
return 0;
}
go to code-runner extention setting and make sure <Code-runner: Run In Terminal>
checked
int main(){ char midInitial;
printf("What is your middle initial? ");
scanf(" %c", &midInitial);
printf("Middle inital %c ", midInitial); (see it should be %c)
}

Store program.exe has stopped working, How can I resolve it?

I'm trying to compile the following code. When I give input to the program then after pressing enter a popup appears which shows that
store program.exe has stopped working
Note: I am using Windows 8.1
Note: I am working on a program (which used in super stores), which includes the following things:
Product code
Product name
Product price
Total bill calculations
It's just the starting.
#include <stdio.h>
int main (void)
{
int d, code;
char product[100], price[100];
printf("\t\t Welcome to the Metro Store\n\n\n\n Enter your product code: ");
scanf("%d",code);
if(code<100)
printf("Pharmacy\n Name of the Medicine");
fflush(stdout);
fgets(product, 100, stdin);
printf(product);
return 0;
}
For starters you should try
scanf("%d", &code);
You have to tell scanf where to write to. If you don't specify the ampersand (&), scanf will not know where is should write to.
You should read the docs and definitely a good introduction to pointers. If you don't understand pointers, programming in C and C++ is pointless ;-)
Then you can change your fgets() to scanf( "%s", product );
In this case scanf does not need the & because product is short for &product[0]. This can get rather confusing, so get to grips with pointers before continuing.
First, scanf() expects a pointer type variable as as an argument to the format specifier. Use
scanf("%d", &code);
^^
Second, do not mix up scanf() and fgets(). Otherwise, the fgets() will end up only consuming the newline left by scanf("%d"..). Try to use fgets() for taking user input to be on safer side. However, if you have to use both, use something like
scanf("%d", &code);
int ch; while ((ch = getchar())!= EOF && ch != '\n');
fgets(product,100,stdin);
to avoid the issue with the leftover newline.

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.

Why doesn't my output show up until the program exits?

I have a simple program from a C programming book, and it's supposed to ask for two integers and then add them together and show the sum. I'm able to enter the two numbers, but the output doesn't show up until the very end of the program.
#include <stdlib.h>
#include <stdio.h>
/* Addition Program*/
main()
{
int integer1, integer2, sum;
printf("Enter first integer\n");
scanf("%d", &integer1);
printf("Enter second integer\n");
scanf("%d", &integer2);
sum = integer1 + integer2;
printf("Sum is %d\n", sum);
return 0;
}
The output looks like this:
2
6
Enter first integer
Enter second integer
Sum is 8
Any help would be greatly appreciated, thanks!
It is possible that the output is not being flushed automatically. You can add fflush(stdout) after each printf() and see if that helps.
Which environment are you using to build and run this program?
Further to the above, printf will only automatically flush it's buffer if it reaches a newline.
If you are running on windows, a newline is \r\n instead of \n.
Alternatively you can do:
fflush(stdout);
Another alternative is to turn off buffering by calling:
setbuf(stdout, NULL);
EDIT:
Just found this similar(but not the same) question:
Why does printf not flush after the call unless a newline is in the format string?

Resources