Advertisement

Basic C help!

Started by June 04, 2000 03:26 PM
16 comments, last by CoiN 24 years, 7 months ago
Lo all, Question 1: How would you prevent the user of your program crashing your program, by entering incorrect data etc String Data into a float. I remember doing it in pascal by reading all data in as a string then converting it with a function called val(), is there a similar type of function in C? Question 2: When displaying floats with printf() how would you make sure that it only displays the number to a certain amount of decimal places. In pascal it was somin like this: Writeln (varname:0:2) To display the number to two decimal places but never mind pascal how do I do it in C? Thanks in Advance.... -=CoiN=-
i think it would be something like printf( "%g " )
Advertisement
i think it would be something like printf( "%g[numdigits] [variable]" ) Stupid board, erased my comments on the above post.
Well, let me see:

1) if a user enters incorrect data, ex. scanf("%f", thefloat); and the user enters in says ''One thousand and one.'' you can probably just ignore the input or just type cast, depending.

2) You use the formating:

/* Myfloat = 1654.435
printf("%.2f", myfloat);
/* Prints out 1654.43 */

Get it? Good. Glad to be of service.



-----------------------------

A wise man once said "A person with half a clue is more dangerous than a person with or without one."
-----------------------------A wise man once said "A person with half a clue is more dangerous than a person with or without one."The Micro$haft BSOD T-Shirt
Not real sure about your first question. I don''t really have time to test something out what I think you do.

As far as your other question, just do this:
printf("Rounded to two decimal places: &.2f ", float_var);
change the two to however many places you want.
Peace Out.
Sorry, that & is supposed to be a % in above post
Advertisement
Thanks Guyz, i now understand how to do my second problem

But im kinda confused on the answer ImmaGNUman gave on the 1st one

How ignore the input cause i though as soon as you read a character or string into a float the program would just crash

And what''s a type cast?

Thanks for the help though ImmaGNUman.


DOH! that was me above this post
int i;float f;i = 10;f = (float)i;  //now we''re typecasting 
Type casting is used to force a cast on a variable.

float f=123.235;
int i=(int)f;


i is typecasting f so it can be an int.


As for the scan, if you do this:

scanf("%d", &Decimal);

If you enter a number, Decimal will have it.
Otherwise, Decimal will be 0, I think. But scanf will return an error, IIRC.
Now I know what I'm made of, and I'm afraid of it...

This topic is closed to new replies.

Advertisement