How can I assign a integer and float values given by user to a variable or array without using scanf()
?
Like we have getchar
,fgetc
,fgets
...etc for char
and string
, Is there any function for floats and integers ?
There aren't functions to read integers and floats but you can use fgets
with strtol
for integers and strtof
for floats:
// floats:
char str_f[20];
float f;
fgets (str_f, 20, stdin);
f = strtof(str_f, NULL);
// integers:
char str_i[20];
int i;
fgets(str_i, 20, stdin);
i = strtol(str_i, NULL, 0);
You can also use atoi
for integers but it's not recommended because atoi
doesn't detect errors and it's considered obsolete.
If you want to detect errors you can use the following code:
// floats:
char *endptr_f;
char str_f[20];
float f;
fgets (str_f, 20, stdin);
f = strtof(str_f, &endptr_f);
if (*endptr_f != '\n' || str_f[0] == '\n' || endptr_f == str_f)
{
printf("ERROR: \"%s\" is an invalid float!\n", str_f);
}
// integers:
char *endptr_i;
char str_i[20];
int i;
fgets(str_i, 20, stdin);
i = strtol(str_i, &endptr_i, 0);
if (*endptr_i != '\n' || str_i[0] == '\n' || endptr_i == str_i)
{
printf("ERROR: \"%s\" is an invalid integer!\n", str_i);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments