C programming elementary problem - c

#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.

Related

Performance - C program takes way longer to run on VS code (windows 10)

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

Code making an infinite loop when ask input with scanf [duplicate]

This question already has answers here:
if my scanf variable is a float and a user inputs a character how can i prompt them to input a number? assuming the scanf is inside a do while loop
(2 answers)
Why is scanf() causing infinite loop in this code?
(16 answers)
I am not able to flush stdin. How can I flush stdin in C?
(8 answers)
Closed 3 years ago.
i have a function that ask to the user to enter a value to calculate its square root, however when i try to validate that the number of the input must be a number and not a char, it makes an infinite loop
void opcion1(void){
float A, K, i, aux;
int awnser;
ask:
fflush( stdin );
printf("enter the value for A: ");
sleep(1);
awnser = scanf("%f", &A);
if(awnser < 1){ // not a number
fputs("\nA is not a number\n", stderr);
goto ask;
}
if(A < 0 ){
aux = -A;
i = sqrt(aux);
if(A == (int)A) printf("\nthe square root of %.0f, is%.0fi", A, i);
else printf("the square root of %.3f, is %.4fi", A, i);
}else{
K = sqrt(A);
printf("the square root of A is %.2f", K);
}
}
output:
enter the value for A:
k
A is not a number
enter the value for A:
A is not a number
enter the value for A:
A is not a number
enter the value for A:
A is not a number
enter the value for A:
The main issue is that its hard to understand all these concepts when you are just starting with the language. Like where the hell does scanf take the input? What is buffering?
I won't talk about technical terms, you can always google them if you want to go deep, will try to keep it simple. Also I am just talking from unix side and donno anything about windows.
scanf(3) calls read(2) internally and printf(3) calls write(2). So why don't we use read(2) and write(2) directly? The issue is that read(2)/write(2) are slow because for them a switch needs to be made to from user mode to kernel mode and this is a time taking process. What scanf() and printf() do is that they stay in user mode and collect the information there and read/write it in one go i.e. they store it in a buffer for time being.
Now this makes some more things possible. As the input hasn't reached your variable yet and is in the buffer, scanf() can do additional checks. Like in your case, check if the input is as per your format specifier. If not it won't assign it to your variable and return. But scanf won't clear that buffer where it received input. In your case in scanf(), when your input is not as per %f, it returns 0 and your if condition makes it go up and input again. But it never cleared the buffer. So the buffer contains the same input as from before and it acts again on it causing the same problem again. This continues infinitely.
Now to the solution:
This is a little confusing due to "standards" issue.
When you see the manpage of fflush(3),
It states:
For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.
But then at the bottom of the page,
The standards do not specify the behavior for input streams. Most other implementations behave the same as Linux.
So fflush(stdin) doesn't seem to work like that on your system. (just as it doesn't on mine)
Best ways to achieve this have already been discussed in many questions:
How to solve your problem:
Scanf skips every other while loop in C
Better way:
Using fscanf() vs. fgets() and sscanf()
Another way is to change fflush(stdin) to fpurge(stdin)(ITS NOT PORTABLE AND NOT STANDARD).
From the manpage of fpurge(3) which I don't see being discussed anywhere:
The function fpurge() clears the buffers of the given stream. For
output streams this discards any unwritten output. For input streams
this discards any input read from the underlying object but not yet
obtained via getc(3); this includes any text pushed back via
ungetc(3).
Also have a look at why its not a good idea to use goto in such scenarios. What is wrong with using goto?

C instructions not executed in order

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.

Replacing gets with scanf in simple equation crashes the program

I'm working through C for Dummies. It has an example code for converting inches to cm (p.135, if you have the text) using gets and atoi.
Now, I wanted to try using scanf rather than the dreaded gets, and this is the best I could come up with (based on the code the author provided).
#include <stdio.h>
#include <stdlib.h>
int main()
{
float height_in_cm;
char height_in_inches;
printf("Enter your height in inches: ");
scanf("%c"),&height_in_inches;
height_in_cm = atoi(height_in_inches)*2.54;
printf("You are %.2f centimetres tall.\n",height_in_cm);
return(0);
}
The program starts, but after input just crashes. Where am I going wrong?
Why spend time converting the answer when scanf() can do it for you?
#include <stdio.h>
int main(void)
{
float height_in_inches;
printf("Enter your height in inches: ");
if (scanf("%f", &height_in_inches) == 1)
{
float height_in_cm = height_in_inches * 2.54;
printf("You are %.2f inches or %.2f centimetres tall.\n",
height_in_inches, height_in_cm);
}
else
printf("I didn't understand what you said\n");
return(0);
}
If you must read a string, then use fgets():
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char line[4096];
printf("Enter your height in inches: ");
if (fgets(line, sizeof(line), stdin) != 0)
{
double height_in = strtod(line, 0);
double height_cm = height_in * 2.54;
printf("You are %.2f inches or %.2f centimetres tall.\n",
height_in, height_cm);
}
return(0);
}
Note that both programs check that input occurred before using the results of the input. You can argue that the error checking for the call to strtod() is woefully lackadaisical; I'd agree. Note that I switched between float in the first fragment and double in the second; either can be made to work. I see no particular reason to limit the input to an integer value when the result will be a fraction. It is also often beneficial to echo the input as well as the output; if what you get echoed isn't what you think you entered, it is a good hint that something is horribly wrong and sends you searching in the right area of the code.
Note: there are a number of minor details brushed under the carpet, especially in the first example regarding float and double with scanf() and printf(). Given the comment below, they are not relevant to the OP at the moment.
Minimal fixes to original code
Since the code above is more complex than the OP recognizes yet, here is a simpler set of fixes to the original code. The string input into an array (string) is the key point; that necessitated changes in the scanf() call too.
By using a big buffer, we can assume that the user won't be able to overflow the input by typing at the terminal. It would not be OK for machine-driven inputs, though.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
float height_in_cm;
char height_in_inches[4096]; // Array, big enough to avoid most overflows
printf("Enter your height in inches: ");
// Missing error check on scanf() — too advanced as yet
scanf("%s", height_in_inches); // Format specifier, parentheses, ampersand
height_in_cm = atoi(height_in_inches) * 2.54;
printf("You are %s inches or %.2f centimetres tall.\n",
height_in_inches, height_in_cm);
return(0);
}
How long is a line of input?
user3629249 commented:
a LOT of stack space can be saved by:
noticing that an 'int' is only a max of 12 characters so the max length on the input buffer is 13 characters (to allow for the NUL string termination byte)
limit the scanf() to 12 characters. I.E. 'scanf( "%12s", myCharArray );
in C, the name of an array degrades to the address of the array, so not leading '&' needed on 'myCharArray'.
Point 3 is correct; if you use char myCharArray[13];, you do not use &myCharArray when calling scanf() et al; you use just myCharArray. A good compiler will point out the error of your ways if you misuse the &.
I have problems with points 1 and 2, though. A lot of trouble can be avoided by noting that if the user types 9876432109876543210 on the line, then using scanf() with %12s is not going to help very much in eliminating invalid inputs. It is going to leave 8 unread digits on the line, and what is read will still overflow a 32-bit integer. If you use the strtoX() family of functions on longer strings instead of atoi(), then they detect problems such as overflow, which neither scanf() with %d nor atoi() do. (This is one of the many points glossed over in the main answer.)
Also, on systems with megabytes, and usually gigabytes of main memory, 4 KiB on a stack is not a major problem. That said, I use 4 KiB in part for its shock value; but POSIX requires a minimum value of [LINE_MAX] of 2048.
If you are reading line-based inputs, which is usually a good way of doing input in command-line applications, then you want to make sure you read the whole line because futzing around with part lines is messy and makes error reporting hard. One major advantage of fgets() plus sscanf() processing is that you have a complete line which you can use in the error report, rather than what scanf() left after processing part of the line. You can also try scanning the string a different way if the first attempt fails; you can't do that with the direct file I/O functions in the scanf() family.
If you naïvely do not recognize that people type long lines when you intended them to type short lines, then you can get leftovers served as a new line — without further user interaction — when it is really the dregs of the previous line of input. For example, if you scan 12 digits out of 20, then the next input will get the remaining 8 digits without waiting for the user to type anything new, even though you prompted them for more input. (Also, beware of using fflush(stdin); it is at best system-specific whether it does anything useful.)
I used fgets() with a 4 KiB buffer. If you want to be safe against programs sending megabytes of JSON-encoded data on a single line, you need to use POSIX's getline() function to read the line. It allocates enough space for the whole line, unless it runs out of memory. For most student practice work, a 4 KiB buffer and fgets() is a reasonable surrogate. I'm willing to negotiate on the power of 2 used as long as the exponent is at least 8 — the value is at least 256. Limiting the line buffer to 80 characters, for instance, doesn't stop the user from entering more than 80 characters on a line. It just means that the extra characters are unlikely to be processed appropriately. Limiting the buffer to 13 characters doesn't buy you anything worthwhile, IMO, and 'saving stack space' is a premature optimization.
You are having troubles with a cast.
atoi accepts a const char* as input.
You are passing a char so it is implicitly casting the char to a point, bad bad thing.
As suggested by user3121023 change height_in_inches into a string.
char height_in_inches[20];
and read using %s
scanf("%s", height_in_inches);

C program console exits immediately after execution?

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.

Resources