Actually return your variable to main.
tabstop is correct. The purpose of endptr is to be assigned to the place where conversion stopped. You'll want to be certain that you stopped in an acceptable location. Here's an example function that's pretty well commented:
Code:
#include <stdio.h>
#include <stdlib.h>
double
input(char array[], unsigned long array_size);
double
input(char array[], unsigned long array_size)
{
double scan;
if( fgets(array, array_size, stdin) != NULL ) {
char * endptr = NULL; /** for tracking the end of conversion **/
scan = strtod(array, &endptr); /** pass the pointer itself **/
if( scan != 0.0 && ( *endptr == '\n' || *endptr == '\0' ) ) {
/** in order for this to be true, the user entered
** something other than zero, and the endptr stopped at either
** a zero terminator or a newline ... **/
return scan;
}
}
return 0.0; /** error **/
}
Just so that you can see how effective it is, I did some simple testing:
Code:
Enter a new item:
12.4
The string recieved was "12.4
"
newItem is 12.4
Enter a new item:
f42.5
The string recieved was "f42.5
"
newItem is 0
Enter a new item:
0.012g
The string recieved was " 0.012g
"
newItem is 0
Enter a new item:
12.4
The string recieved was " 12.4
"
newItem is 12.4
Enter a new item:
one
The string recieved was "one
"
newItem is 0
Press any key to continue . . .
There are some flaws, like how it is perfectly acceptable to have whitespace before the number. But with a little thought, you can be very stringent. If all else fails, try inventing some custom validation.