I'm a real newbie in C but I'm willing to learn a lot, and I have written this very simple program, in which the user is asked to type a number with the keyboard. Before that, the message "Please type a real number with the keyboard" should be displayed, and after, a message confirming to the user the value of the number they typed. (code below)
The problem is, when I build my executable and then run it, it first asks for the value of x, and displays the message "Please type a real number with the keyboard" only after the user typed a number! What did I do wrong?
Could someone explain me this weird behaviour, since I typed my instructions in the good order?
#include <stdio.h> /* package to read and to write variables */
int main(void) /* main program */
{
float x; /* declaring a real number x*/
printf("Please type a real number with the keyboard\n");
scanf("%f", &x); /* prompting x with the keyboard */
/* displaying x : */
printf("You just typed %f, congratulations !", x);
return 0;
}
It is likely that there is quirk with the program displaying your output and how it buffers lines. Most outputs will buffer and display per line (that is your output will be saved up until a \n char is seen). To fix this you can either force the command to flush with fflush(stdout), or you can change how you are viewing the output. This might mean running your program on the command line.
Related
I have just installed visual studio code & after watching some basics, I have written a simple C code to calculate area of rectangle. But, when I run the code its taking too long to execute.
My system configuration are 4gb RAM, i3 - 5th gen (poor boi) Here is the code:
#include <stdio.h>
int main()
{
int l;
int b;
printf("enter the length of rectangle in an integer value");
scanf("%d ", &l);
printf("enter the breadth of rectangle in an integer value");
scanf("%d ", &b);
printf("the area of rectangle is %d", l * b);
return 0;
}
Change scanf("%d ", &l); to scanf("%d", &l); and scanf("%d ", &b); to scanf("%d", &b);.
A space in a format string tells scanf to read from input until a non-white-space character is read. So, after scanf("%d ", &l);, the program continues reading input until you type something such as the next number. If you do type that next number, then scanf("%d ", &b); reads it and then continues reading until it sees another character that is not a space. As long as you do not type anything, or type only spaces and returns/enters and other keys that generate white space characters, the program continues waiting.
Removing the spaces eliminates this.
The program is not “taking too long to execute.” In fact, the program is waiting for user input, so it is just waiting, not executing. Because it did not complete, you concluded it was taking too long to execute. Instead of reporting a conclusion, you should have reported the observed behavior: After typing input, there was no visible activity by the program.
Skipping spaces before performing a conversion is built into most scanf conversions, such as %d. Only include a space character in a format string where you want to skip spaces that would not be skipped normally, such as before a %c conversion, which does not have the automatic skipping built in.
Also, in printf("the area of rectangle is %d", l * b);, add a new-line character at the end, printf("the area of rectangle is %d\n", l * b);. (This ensures the prompt printed by a command-line shell after the program finishes executing is on a new-line, so it will not be confused with the program output. C is designed to end lines of output with new-line characters, so you should make it a regular practice.)
Alright guys, I found the solution. The first thing I want to apologize is that the code is not taking too long to execute. The code is actually executing but there was no visible activity. Everything in the code is just perfect. The mistake I made is I didn't change one setting in VS Code. I use code runner extension to run my codes [that's the most popular]. I have to go in File --> Preferences --> Settings --> Type 'code runner' in the search bar --> check the setting given in this image - https://drive.google.com/file/d/1QwB2NjKpYX7M0b5w55sqy4oMVAOk_IK2/view?usp=sharing
Lot of people were trying to figure out a mistake in the code, but there is nothing wrong with it. Code runner was not able to run in the terminal, so there was no activity to take any user input - due to read only text editor. After changing that setting I was able to give user input directly in the terminal.
Credit for the solution - https://www.youtube.com/watch?v=Si8rN5J249M
EDIT: There is a mistake in my code also lol, which is mentioned in another answer - Really appreciate it Eric Postpischil
I'm new to programming in C and I'm trying to build and execute my first programs. My first program was Hello, World printed in the CMD like many of you. It worked great. Now it's onto bigger and better projects though and I'm having a weird issue.
I'm trying to make a basic addition calculator using standard IO operations (scanf and printf) and it won't function properly.
My program asks for 2 numbers to be input by the user and it will then display the output of said calculation. The program executes flawlessly until the scanf expression comes into play. After I input my 2 numbers to be added the CMD prompt just closes without warning and never spits out an answer or the text I have to be displayed afterward.
I tried multiple solutions to fix this problem including copying and pasting the source code directly from the website I was learning from, even their perfect code nets the same outcome..just a crash before an output is displayed. I'm posting today because I'm wondering where my issue is coming from because I'm just not sure why this program won't execute as it's supposed to. Thanks in advance and heres the code I'm working with:
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter two numbers to add\n");
scanf("%d%d", &a, &b);
c = a + b;
printf("Sum of the numbers = %d\n", c);
return 0;
}
Once console application returns from main method, the associated console window closes automatically. I assume you are using Windows OS. In that case add a system("pause"); before your return 0; statement.
For platform independent solution you can just show a prompt to user and wait for a key press before returning from main. As #chux pointed out in comment any character remaining in input buffer (enter from scanf in this case) must be cleared.
#include <stdio.h>
int main()
{
int a, b, c;
printf("Enter two numbers to add\n");
scanf("%d%d", &a, &b);
c = a + b;
printf("Sum of the numbers = %d\n", c);
//clear input buffer
int d;
while ((d = getchar()) != '\n' && d != EOF) { }
printf("Press ENTER key to Continue\n");
getchar();
return 0;
}
CMD prompt just closes without warning and never spits out an answer
Seems like you are opening a new terminal on Windows machine. I compiled the code and it works. Your program closes just after printing the answer so you simply cannot see it. Stop it artificially before the end. To prove it add the following line directly before return:
scanf("%c", &a);
This will result in stopping the program and waiting for input. You will need to enter another number which will essentially be ignored but will stop the program so you can see the output. This is not a good target solution though due to you need to enter some characters to go on and exit but it proves the point :)
I am using Code::Blocks for programming and yeah i am a beginner but everytime i write a program it pauses in IDE but does not pause while executing directly.
What is the possible reason ? Can anyone explain me ?
My code goes as follows :
#include <stdio.h>
void main()
{
float length,breadth,Area;
printf("Enter the value of length and breadth \n\n");
scanf("%f %f",&length,&breadth);
printf("You entered length=%f and breadth=%f \n\n",length,breadth);
Area= length * breadth;
printf("The area of the rectangle is %f\n\n",Area);
return 0;
}
You have to tell your program to wait for input at the end otherwise it will execute, do exactly what you wrote in your code and exit. The "good" way would be to execute it from a terminal (cmd if you are on windows)
#include <stdio.h>
int main()
{
float length,breadth,Area;
printf("Enter the value of length and breadth \n\n");
scanf("%f %f",&length,&breadth);
getchar(); // catch the \n from stdin
printf("You entered length=%f and breadth=%f \n\n",length,breadth);
Area= length * breadth;
printf("The area of the rectangle is %f\n\n",Area);
getchar(); // wait for a key
return 0;
}
Why do you need a getchar() after your scanf()?
When you enter your numbers you finish it with a press of enter. Let's see what you are reading: a float whitespaces and another float. The \n is not consumed by scanf(), but left in the input buffer (stdin). The next time you use a function that reads from stdin, the first sign this function sees is a \n (Enter). To remove this \n from the input buffer you have to call getchar() after scanf() which reads 1 character from the input buffer. I'm sure you will encounter this behaviour more often in future.
As a really, REALLY bad practise, you can just use a getch call to stop the excecution (or any function that generates a small pause, getch is not a standard function).
A program is not supposed to pause after execution and this is a feature added by the IDE. If you want execution to pause and wait for some input you should instruct it to do so. For instance if you are on windows you can add a line:
system("pause");
Right before return 0;. This is not advisable, but may help you for debugging in some cases. Also the standard requires that your main function is int, not void. So you better get used to writing int main instead of void main.
You need to use getch(); at the end of program (Before return statement)
Getch holds down the output screen.
So basically I have a a program in C, whose point is to look organized.
I'd like my program's cursor not to move after I confirm my Scanf statement.
Heres example part of my program and its output:
#include <stdio.h>
int main()
{
char input[10];
int voltage=220;
printf("What do you want to know\n"); //no need to correct me on this part please
scanf("%s", input);
if (strcmp("voltage",input)==0)
printf(" = %d\n", voltage);
/* Imagine other string comparisons (resistance, current) here*/
return 0;
}
So this program for input "voltage" would output something like this:
voltage //what I just inputed via scanf
= 220 // \n because I pressed enter after inputing.
What I wanted is:
voltage = 220
I dont know Is there reverse \n function that I dont know about.
There is no standard way in C to read input without pressing Enter. You will have to go for platform specific functions.
There are lots of questions here in StackOverflow that cover this, such as Capture characters from standard input without waiting for enter to be pressed
#include <stdio.h>
#include <math.h>
int main (void)
{
float inches;
printf("Enter the number of inches\n");
scanf("%f\n",&inches);
float feet;
float cm;
float yards;
float meter;
feet = 12 * inches;
cm = 2.54 * inches;
yards = 36 * inches;
meter = 39.37 * inches;
printf("Amount in feet: %f\n", &feet);
printf("Amount in cm: %f\n", &cm);
printf("Amount in yards: %f\n", &yards);
printf("Amount in meters: %f\n", &meter);
getchar();
return 0;
}
I'm using Dev c++
Is the problem i'm problem I'm working on in C. Basically enter in a number in inches then print amount in cm,yards,meters and feet. This is giving me 0.0000 or something for all of them or actually the time it is up. I can't keep the screen up and I thought that was the purpose of getchar() but I must have been mistaken. Any help is great. Thanks!
EDIT 1
What about as far as keeping dev c++ on the screen instead of closing out after I put stuff in? I am also having to put 2 values in before it returns in anything when the screen pops up? Why??
Two problems:
The usual problem with using scanf(), in that it leaves the newline after the number unread and the following read operation (the getchar() here) reads it.
You shouldn't pass pointers to printf(), but the actual values.
You're trying to print the addresses of your floats as floats, you just want to say this:
printf("Amount in feet: %f\n", feet);
Note the lack of an address (&) operator on feet. You want to apply similar changes to your other printf calls.
With printf, you don't give it the address of the float values, you just give it the values. Remove the &s from the printf calls.
You need the address in scanf because the function modifies the variables that you pass in, but printf just needs the values. As it is, the printf is essentially reinterpreting the pointers as floats, which is why you get the garbage values displayed.
About I can't keep the screen up, it's a common problem to everyone trying to execute a console program in a graphical environment directly from the IDE, in particular Dev-C++. The problem is that there's no console for I/O, then one is provided but just for the time the program is running, and since programs are fast, if you do not add a pause after your last input and output, you won't have the time to read the output.
Many MS Windows Dev-C++ users add an horrorific system("pause"). I always suggest that, if Dev-C++ is not able to provide a console for I/O with the option "keep it opened even after the program ends", then it is better you open a shell (cmd or powershell on windows) and run your program directly from there.
About the input problem, unluckly scanf-ing has several buffering problem since the input that is not recognized for the given format is not discarded and is ready for the next reading. E.g.
scanf("%f", &aFloat);
scanf("%f", &theNextFloat); // in your case you have the extra getchar();
won't stop for the second scanf if you write 1.25 4.5 as first input, since the 4.5 is already available for the next scanf. In your case it was a newline that was left in the buffer and since getchar has found it, it does not need to wait for input. You could use a
while( getchar() != EOF ) ; instead, and then to exit you need to hit Ctrl-D.