Issue
(System: Linux Mint 18.1)
How can i achieve an EOF by pressing [CTRL]+[D] at scanf()
?
At the time it only works with [CTRL]+[C],
however our task is to achieve it by [CTRL]+[D] explicit in scanf()
.
My function is the following:
float getFloat1()
{
float num = 0.0;
char term;
char loop = 'y';
while (loop == 'y')
{
printf("Please enter a number: ");
if (scanf("%f%c", &num, &term) != 2 || term != '\n')
{
printf("[ERR] Invalid input.\n");
while ((getchar()) != '\n'); // Flushes the scanf() input buffer
}
else
{
printf("[OK] Valid input: %f\n", num);
loop = 'n';
}
}
return num;
}
I am grateful for any help, links, references and hints!
Solution
Use a variable to store the result of scanf. Then compare the variable in the block to see if EOF was captured.
float getFloat1()
{
float num = 0.0;
char term;
char loop = 'y';
int result = 0;
while (loop == 'y')
{
printf("Please enter a number: ");
if ((result = scanf("%f%c", &num, &term)) != 2 || term != '\n')
{
if ( result == EOF) {
printf ( "EOF\n");
break;
}
printf("[ERR] Invalid input.\n");
while ((getchar()) != '\n'); // Flushes the scanf() input buffer
}
else
{
printf("[OK] Valid input: %f\n", num);
loop = 'n';
}
}
return num;
}
Answered By - xing Answer Checked By - Terry (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.