How to identify the end of input?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Parul Vinod
    New Member
    • Aug 2011
    • 36

    How to identify the end of input?

    Problem Definition:
    rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits.
    Example
    Input:
    1
    2
    88
    42
    99

    Output:
    1
    2
    88

    My code:
    Code:
    #include<stdio.h>
    void main()
    {
    int nomore,i,j,output[100],number;
    nomore=5;
    i=0;
    while(scanf("%d",&number))
    {
    if(number==42)
    {
    nomore=0;
    }
    if(nomore!=0)
    {
    output[i]=number;
    i++;
    }
    }
    for(j=0;j<i;j++)
    {
    printf("%d\n",output[j]);
    }
    }
    here the while loop is not breaking. So, how will i come to know that the input is over?
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Because you never break out of it and you don't have a condition in the while that would cause it to break either.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Generally, you can't tell when the end of input occurs since more old be coming as soon as the user gets back from a coffee break. So you kind of wait forever.

      The user will have to close the iput stream by signalling end-of-all-input. For console applications, this is usually CTRL+Z and this will show up in your program as EOF.

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        It is up to you to specify how you want the user to tell the program that input is complete. Here are some possibilities, but it is really up to you to decide what makes the most sense for how your program is used.
        1. Ask the user to tell you how many input values there will be before any of those values are entered.
        2. Explicitly ask the user to tell you if there is more input after each value is entered.
        3. Use CTRL-Z (ASCII EOF) to signal that input is complete. (Not all C implementations use ASCII.)
        4. A specific kind of illegal value implicitly indicates that there is no more input.
        5. Your program could be hard-coded to only accept precisely N input values.
        6. Something else that you think of.

        Comment

        Working...