0

In the find.c there is the following code

for (size = 0; size < MAX; size++)
    {
        // wait for hay until EOF
        printf("\nhaystack[%i] = ", size);
        int straw = get_int();  // ??? get 2nd  argument from ./generate (argv[1]); number random integers
        if (straw == INT_MAX)
        {
            break;
        }

        // add hay to stack
        haystack[size] = straw;
    }

If I use this command ./generate 1000 50 | ./find 127

How it count to haystack[1000] =? From where and how it takes 1000?

I suppose from int straw = get_int(); where get_int() somehow takes 2nd argument from generate.c (argv[1]); number random integers ) one by one ( int straw = get_int(); ) and put it to haystack[size]. But I don't undersand how.

1 Answer 1

1

get_int() has no knowledge of the "2nd argument from generate.c". Remember from the spec:

You’ll be prompted to provide some hay (i.e., some integers), one "straw" at a time. As soon as you tire of providing integers, hit ctrl-d to send the program an EOF (end-of-file) character. That character will compel get_int from the CS50 Library to return INT_MAX, a constant that, per find.c, will compel find to stop prompting for hay.

When find gets an EOF "signal", it stops prompting for hay.

If you run this ./generate 1000 50 (without the pipe to find), it will produce a list of 1000 numbers. When it is done system (internally) knows it has reached EOF and signals that, and therefore stops prompting for hay.

1
  • int straw = get_int(); // It can get for example 1,000 or MAX = 65536 pseudorandom numbers from ./generate 1000 via pipe | ./generate 1000 50 | ./find 127 and then find needle? " In turns out you can automate this process of providing hay, though, by "piping" the output of generate into find as input. " Thank you @DinoCoderSaurus!
    – Yellowfun
    Commented Feb 13, 2017 at 16:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .