Matt
Matt

Reputation: 69

Incorrect output. C++ primer 1.4.4

the following program is supposed to count the number of times a user inputs a integer. example: user inputs 42 42 10 10. the program is supposed to out put : 42 occurs 2 times, 10 occurs 2 times.

the problem: the code will not output the last result for the number 10 until you input another number. i have pasted the code below. this code comes from c++ primer. 1.4.4

#include <iostream>
int main()
{
    // currVal is the number we're counting; we'll read new values into val
    int currVal = 0, val = 0;

    // read first number and ensure that we have data to process
    if (std::cin >> currVal) 
    {
        int cnt = 1;  // store the count for the current value we're processing

        while (std::cin >> val) 
        { // read the remaining numbers

            if (val == currVal)   // if the values are the same
                ++cnt;            // add 1 to cnt
            else 
            { // otherwise, print the count for the previous value
                std::cout << currVal << " occurs " << cnt << " times" << std::endl;
                currVal = val;    // remember the new value
                cnt = 1;          // reset the counter
            }

        }  // while loop ends here

        // remember to print the count for the last value in the file
        std::cout << currVal <<  " occurs " << cnt << " times" << std::endl;
    } // outermost if statement ends here

    return 0;
}

Upvotes: 0

Views: 725

Answers (1)

Joe Z
Joe Z

Reputation: 17946

Your program as-written appears correct for a series of numeric inputs separated by whitespace.

You need to give an end-of-file indication to the program so that it will exit the while loop and print the count for the final data. In Windows, you can do that by entering [Ctrl]-[Z] as the first character on a new line. In Linux, UNIX and Mac OS X, [Ctrl]-[D] serves a similar purpose.

Alternately, you can put your set of values into a text file and use redirection to feed your program. Suppose, for example, you put your data in a file named data.txt in the same directory as your executable. In a terminal window, you can run your program as follows:

myprogram < data.txt

As some others have noted, a non-numeric input will also work in place of end of file. For example, you could enter 42 42 10 10 fred, and it'll output what you expect as well. That doesn't appear to be the intent of the program, though. For example, if you input 42 42 10 10 fred 37, the program stops at fred and won't see 37.

Upvotes: 2

Related Questions