Friday, July 31, 2009

C Programming - Reading input from STDIN - need help.?

I need to write a program in pure C. Coming from a C++/Java background I am slightly confused.





I would like to read in a float value from STDIN. I see there are functions like read(), scanf().... that will let you read in char[], but nothing to read in something else.





So how can a read in a float, or how would I convert a char[] to a float.

C Programming - Reading input from STDIN - need help.?
#include %26lt;stdio.h%26gt;





int main() {


float x;


printf("Enter a float value for x: ");


scanf("%f",%26amp;x);


return 0;


}





printf will put the string give to the standard output (this case the console).


scanf will read from the standard input.. Because it accepts any number of parameters (which are adresses to variables declared in the program) you must specify what to expect in the string given at the input. %f means here you must read a float.. If I added %f %d for example it meant fisrt try to read a float until you find a blank then try to read an integer...


printf also accepts any number of parameters and if you want to show variables you have to do exactly the same thing as for scanf.. So if I were to show the x value I would write


printf("The value for x is : %f",x); (instead of %f it will put the float value of x... if x was declared as an integer it will automatically convert it to float and then show it- implicit conversion)... and so on. :)


You'll find the documentation for printf fprintf, scanf fscanf and lots more on the internet... (look here : http://www.cprogramming.com/)

survey for cash

No comments:

Post a Comment