My C code is not responding after scanf statement - c

I have wrote a set of code that scan in values and use them to test out central limit theorem. However when I run my program after I input all the values using scanf my program is not proceeding to the next lines of code : the problem looks like this:
printf("*** DEMONSTRATION OF CENTRAL LIMIT THEOREM ***");
printf("Enter parameters for the distribution [a b] ==> ");
scanf("%f %f",&a,&b);
printf("Enter distribution to display [1=data, 2=mean] ==> ");
scanf("%d",&option);
printf("Enter number in each group ==> ");
scanf("%d",&group);
printf("Enter number of samples of groups ==> ");
scanf("%f",&times);
printf("are we here yet");
after these printf and scanf the program starts to do the calculations. But When I run the program after I compile(successfully). It seems my code is stuck after the scanf("%f",&times);
the line "are we here yet" never gets printed, meaning the program did not get past the scanf. I have not done much C programming this seemed really strange to me can someone figure out why the program is not excuting past the line scanf("%f",&times); I really appericate it

Input/output at the terminal is line-buffered in C, and output is not going to display until you output a newline character, or you call fflush(stdout), or your program terminates normally and all the buffers are flushed anyway. Change:
printf("are we here yet");
to:
printf("are we here yet\n");
or:
printf("are we here yet");
fflush(stdout);
and you should see your output.

Related

Program accepting input but does not give output

#include<stdio.h>
#include<conio.h>
int main()
{
clrscr();
int a,b,c;
printf("enter the 2 numbers: ");
scanf("%d %d",&a,&b);
c=a+b;
printf("the sum is : %d ",c);
return(0);
}
this is a simple program to add 2 numbers.
my program would let me input the value..but it would not print the sum ,nor would it print the next line.
it would run till the scanf() and as i press enter, it would jst exit the program.
can you please tell me whats wrong. I am a beginner programmer...
There are two things you should think of here.
End printouts with a newline character, because stdout is often line buffered. Do printf("the sum is : %d \n",c); instead. Or call fflush(stdout); expliticly after the printout. This will ensure everything gets printed.
Add some input code in the end. Like an extra scanf("%d", &a); This is basically a small hack to prevent the window from closing before you can see the final output. Another alternative is to add sleep(3); to sleep for 3 seconds. A third alternative here is to see if there are some settings that controls the closing of the window in your IDE.
Your program works correctly, but it exits right after printing the output, giving you no time to look at it.
Consider adding some input before return(0);, such as 2 getchar(); calls. You need 2, because the first character read will be the \n that you typed after the numbers.

Redirect C output to a txt file

I am redirecting program output to a txt file and entering the values prompted by the main function:
I expected my output.txt file to have the following data:
Enter float1: 2.4
Enter float1: 4.6
But instead, it has this:
Enter float1:
Enter float1:
Here is my main function:
printf("Enter float1: ");
scanf("%f", &float1);
printf("Enter float2: ");
scanf("%f", &float2);
Can anyone please help to redirect inputted values as well?
I researched the question but I couldn't find anything that would solve the problem.
I tried redirection stderr to see if the values are printed there but it gave me an empty file.
The user input is stdin but you are redirecting only stdout to file. Hence you will see in the output.txt only what your program prints to stdout. If you want to print entered values, you have to print them after scanf.
In the example below, you should see also input values in your output.txt
printf("Enter float1: ");
scanf("%f", &float1);
printf("%f\n", float1);
You got the two values with scanf() but you didn't print them (with printf() for example), so they don't appear in stdout.
When we input something on the standard input with the keyboard, we can see the text just because the terminal (not your program) echoes these characters.
So, redirecting your program's standard output does not change anything to that.
Change your main to:
printf("Enter float1: ");
scanf("%f", &float1);
printf("%f\n", float1);
printf("Enter float2: ");
scanf("%f", &float2);
printf("%f\n", float2);
On a side note, if you're confused about redirection, printf is a modified version of fprintf. Printing to the console is just so common there's a function for it. Saying printf("%f\n", float1) is the same as fprintf(stdout, "%f\n", float1). Same goes for scanf vs. fscanf. Redirecting output allows you to keep your printf statements in your code, yet still print to a file. Else you would have manually change them all to fprintf which would be a pain.

scanf always prints entered number

Just started learning C and I have a problem with the scanf function. Every time I enter a number in the console, it will be printed right under the input. The program still works, but it is a little bit annoying.
(I am using CLion from JetBrains)
int main()
{
int x;
printf("Number: ");
scanf("%d", &x);
printf("Your number is %d!", x);
}
This is the output:
Number:15
15
Your number is 15!
Process finished with exit code 0
It is an issue in clion (Why is CLion printing back inputs from standard input?). Currently unresolved. This problem exist for C and C++.
This bug resides for four years. I definitely advice you to change your compiler if you are not bound this for a particular reason.

Unable to execute a do-while loop completely [duplicate]

This question already has answers here:
Yes/No loop in C
(3 answers)
Closed 8 years ago.
I am trying to execute a small program using do-while.
#include<stdio.h>
#include<conio.h>
void main()
{
char another;
int num;
do
{
printf("Enter a number");
scanf("%d",&num);
printf("Square of %d id %d",num,num*num);
printf("Want to another another number y/n");
scanf("%c",&another);
}while(another=='y');
}
Now when I try to execute the program, it runs fine. I input a number and it displays its square. And then I see Want to enter another number y/n. But as soon as I press any key (y or n), the program exits itself before I can press enter to provide the input. I tried it many times but no success.
But the program runs fine if I ask the user to input either 1 or 2(in place of y/n). In that case it takes an integer input and can check the while block. If another == 1, the program runs again.
My problem is that why can't I check for a character in the while condition.
The reason it doesn't work is that after scanf gets num, the new line is still in the buffer, so it will be processed by the next scanf with %c format specifier. A direct way of fixing it is to use:
scanf(" %c", &another);
// ^space
Note that your original scanf("%c:,&another); won't compile, but I assume that's a typo. And always use int main, or it's undefined behavior.

Placement of function to restart loop in C

I've put together a simple currency converter program from code I've edited from the web and a switch statement that I've put in. When I ran the program in Visual Studio:
printf("Would you like to make another conversion? y/n\n");
fflush(stdin);
scanf("%c",&marker);
would wait for input and then either go back to the start of the while statement or exit the console window. Now if I run this is Xcode on a mac "Would you like to make another conversion..." is printed but doesn't wait for an input, it just goes straight back to the while loop.
Am I putting the printf("Would you like...etc section in the right place? Or is there a better way of getting loops to run again after they take input from a user? Do I need to do anything with a 'bool' statement. We've not got that far in class yet.
Full code is shown below:
#include <stdio.h>
int main ()
{
int choice;
float money;
float total;
char marker='y';
printf("\n\nCURRENCY CONVERSION\n");
printf("***Rates correct as of 26 NOV 12***\n");
printf("------------------------------------\n");
printf("1. Australian Dollar (AUD) 1.533=1 GBP\n");
printf("2. Euro (EUR) 1.235=1 GBP\n");
printf("3. Indian Rupee (INR) 89.494=1 GBP\n");
printf("4. Japanese Yen (JPY) 131.473=1 GBP\n");
printf("5. US Dollar (USD) 1.602=1 GBP\n");
printf("Enter the number for the currency to convert...");
while(marker!='n')
{
printf("\n\nWhat would you like to convert your money to? (1-5): ");
scanf("%d",&choice);
printf("\n\nHow much money do you want to convert? (GBP): ");
scanf("%f",&money);
switch(choice) {
case 1:
total = money * 1.533;
printf("\n\nYou will have %.2f Australian Dollars \n\n", total);
break;
case 2:
total = money * 1.235;
printf("\n\nYou will have %.2f Euros \n\n", total);
break;
case 3:
total = money * 89.494;
printf("\n\nYou will have %.2f Indian Rupees \n\n",total);
break;
case 4:
total = money * 131.473;
printf("\n\nYou will have %.2f Japanese Yen \n\n", total);
break;
case 5:
total = money * 1.602;
printf("\n\nYou will have %.2f US Dollars \n\n", total);
break;
default:
printf("You did not choose a correct option\n");
}
printf("Would you like to make another conversion? y/n\n");
fflush(stdin);
scanf("%c",&marker);
}
return 0;
}
Many thanks for any comments of input received.
Your problem is likely that the scanf("%c", &marker); is reading a newline left over by a previous input.
Note that fflush(stdin) invokes undefined behaviour. The C standard says of fflush():
If stream points to an output stream or an update stream in which the most recent operation was not input, fflush() shall cause any unwritten data for that stream to be written to the file.
If that operation clears the input queue in Visual Studio or on Windows, then you've just learned the hard way that extensions to the standard on one platform do not always work on other platforms. In particular, fflush(stdin) does not clear queued characters waiting to be read.
Note that you could have helped your debugging efforts by printing the erroneous input as part of the error message.
You should also be testing each scanf() call:
if (scanf("%c", &marker) != 1)
...EOF or other problem...
if (scanf("%f", money) != 1)
...EOF or maybe a letter instead of a number...
Stylistically, it is best to include a break; after the code after the default: label in the switch.
Also, you should really avoid repeating the conversion rates in the strings that are printed in the menu and in the case statements. Similarly with currency names. Maybe you haven't covered arrays and structures yet, but in the long term, that is a recipe for problems (if only wasted recompilations because the rates have changed; but allowing them to be read from a file, or a web site, is another major exercise).
This isn't anything to do with the loop. It's about your calls to scanf.
What's happening is that stdin is buffered. scanf will only cause the program to halt and wait for input if there isn't enough pending data in the buffer. When you do this:
scanf("%f", &f);
...then the program will halt until you type a line of text. Say you type:
1\n
The 1 is read into the variable f... but the newline remains in the buffer.
This means that your call to:
scanf("%c", &c);
...will return immediately, because there's enough data in the buffer to complete the call. The program will only stop and wait for more data when it runs out of buffer.
Windows doesn't do buffering like this, which is why you weren't observing the behaviour there.
There are about a million solutions to this, ranging from changing the way stdin is buffered to using a text-based UI library like ncurses. Given that by default stdin is line-buffered --- data is read a line at a time, terminated with newlines --- the simplest is simply to make sure that each call to scanf() consumes a complete line of text. That means that the buffer will be empty each time you call scanf. For example:
scanf("%f\n", &f);
...and:
scanf("%c\n", &c);
BE AWARE that if the user enters input that doesn't match this format string, such as 1 2 for the first or ab for the second, scanf will leave the variable uninitialised. So you absolutely have to check the return parameter.
if (scanf("%f\n", &f") != 1)
error("Oh noes!");
Otherwise your program will go horribly, horribly wrong.
As an aside: you haven't done it in this program, but just so you're aware, scanf("%s") should not be used. For anything.
You can do an infinite loop(eg. while(true){} ), and in your switch statement have a case for choice 'n' that breaks the loop (eg. break;)
Also, case 1 , case 2, etc... I would scan them as chars instead of integers. (eg. case '1':, case '2':, etc...)
I am not sure what I just said is going to work but that is my initial thought. Hope it helps :)
If you don't want to deal with flushing buffers, you can define a char buffer[1024] and use fgets with sscanf:
printf("\n\nWhat would you like to convert your money to? (1-5): ");
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%d", &choice);
and the while loop can include your menu:
while (1) {
printf("\n\nCURRENCY CONVERSION\n");
printf("***Rates correct as of 26 NOV 12***\n");
/* ... */
printf("Would you like to make another conversion? y/n\n");
fgets(buffer, sizeof(buffer), stdin);
sscanf(buffer, "%c", &marker);
if (marker == '\n')
break;
}

Resources