PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

[FIXED] How can i achieve an EOF by pressing [CTRL]+[D] at scanf()?

 October 30, 2022     c, eof     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing