Using CTRL+X to end a stream?

Hi,

So for my computer science class I need to create a program that allows a user to input an indefinite number of numbers (as many as they want), and then print the average of the numbers. But, the user is supposed to enter "CTRL+X" to indicate they are done inputting numbers. I have no idea of how to go about doing this.

My class's problem statement is as follows:
Write a program that allows a user to input a stream of numbers and computes their average. The user can enter as many numbers as she wants, signaling the end of the stream by pressing <CTRL> X. Use main() to instruct the user and print the answer . Use a function to take in the user inputs, keep a running total and a count, compute the average and return it.

Help!?
Very strange thing.

End of input is signaled by Ctrl-Z on windows or Ctrl-D on linux machines. Stream reading functions understand these special characters all right.

Ctrl-X is something new to me. I could not find at once whether this sequence is recognized by system. Which OS you are using, by the way?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

int main()
{
    constexpr int ctrl_x = 24 ; // or whatever it is on your implementation

    int cnt = 0 ;
    double total = 0 ;

    double number ;
    while( std::cout << "number? " && std::cin && std::cin.peek() != ctrl_x )
    {
        if( std::cin >> number )
        {
            ++cnt ;
            total += number ;
        }

        else
        {
            std::cout << "please enter a number or ctrl-x to quit\n" ;
            std::cin.clear() ; // clear the error state
        }

        std::cin.ignore( 1000, '\n' ) ; // empty the input buffer
    }

    if( cnt > 0 ) std::cout << "average is: " << total / cnt << '\n' ;
}
Topic archived. No new replies allowed.