You are posting in the right forum, don't worry!

There are many different methods to do input validation, the most elegant being

REGular EXpressions (or REGEX for short) which has only recently been standardized as a part of C++11's standard library. Using it is very easy, but is considered a C++ solution so it might not be an acceptable answer. But I strongly urge you to use it if possible:

- Code: [Select all] [Expand/Collapse]
#include <stdio.h> // printf(), scanf()

#include <stdlib.h> // atoi(), atof()

#include <regex> // regex, regex_match()

char * input;

unsigned int positive_int;

float natural_number;

int main()

{

// regular expressions which has the format you desire to match later

regex is_positive_integer(R"(\+)?[[:d:]]+)");

regex is_natural_number(R"((\+|-)?(([[:d:]]+\.)|(\.))?[[:d:]]*)");

scanf("%s",&input);

if (regex_match(input, is_positive_integer))

{

// atof(): Array_TO_Float

natural_number = atof(input); //convert string input to float

printf("input is a natural number! %d", natural_number);

}

if (regex_match(input, is_natural_number))

{

// atof(): Array_TO_Float

natural_number = atof(input); //convert string input to float

printf("input is a natural number! %d", natural_number);

}

return 1;

}

- GeSHi © Codebox Plus

The pure C solution is a pretty ugly (hey! an oxymoron!) one, and would essentially be building from what Rhino has written in his post. You'll have to consider the following though:

[*]A number can start with either a sign, digit or a period. ("-321", "+516.3", "142.5", ".667")

[*]A period can only appear once in the number; in the beginning, after a sign (eg: "-.6") or somewhere after a digit.

[*]A digit can appear anywhere else.

Using the rules above, you can construct a "IsValidNaturalNumber( )" function which will return "true" if the string you pass to it is a a number:

- Code: [Select all] [Expand/Collapse]
//#include <stdio.h>

//#include <stdlib.h>

//#include <ctype.h>

//#include <string.h>

bool IsValidNaturalNumber( const char * test_string )

{

// first we declare our flags

bool is_start; // true if the character we're dealing with is the first in the string

bool has_period; // true if the string has a period in it already

has_period = false;

for (int i

= 0; i

< strlen(test_string

); i

++) {

is_start = i == 0;

char character = test_string[i];

continue;

if (is_start && (character == '-' || character == '+'))

continue;

if (is_start && character == '.')

{

has_period = true;

continue;

}

if (character == '.' && !has_period)

{

has_period = true;

continue;

}

// if no condition is satisfied

return false; // verdict: isn't a number

}

// if all characters satisfy the conditions

return true; // verdict: is a natural number

}

- GeSHi © Codebox Plus

Then if the string you enter is a valid number, you can then use "atoi" or "atof" to convert them.