-2

So as the title says, I dont want to use system("pause") because I dont want to develop a bad habbit. And I cant figure out why it keeps closing even though I have cin.get();

#include <iostream>

using namespace std;


float medel(int v[], int n)
{
    float res = 0.0;

    for (int i = 0; i < n; i++) 

    {
        cin >> v[i];

        res += ((double)v[i] / n);
    }

    return res;


}

int main() {
    const int num = 10;
    int n[num] = { 0 };

    cout << "Welcome to the program. Enter 10 positive numbers: " << endl;;
    cin.get();
    cout << "The average of ten numbers entered is: " << medel(n, num) << endl;
    cin.get();
    return 0;
}
JohnA
  • 564
  • 1
  • 5
  • 20
  • char x, while(x != 'q') {cin.get();} – Omid CompSCI May 03 '17 at 17:48
  • 3
    How are you learning C++? `cin.get();` is not going to read in 10 numbers and it also it not storing what it did read in into anything. Sounds like you could use a [good C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – NathanOliver May 03 '17 at 17:50

1 Answers1

4

cin.get() consumes a single character from your input stream.

If there isn't one already there, the program will block waiting for one, which is your expectation.

However, there is one there: the newline from the Enter keypress after your last cin >> v[i] operation.

Don't use cin.get() to keep your application running at the end, anyway.

By the way, your program's logic is flawed; you seem to prompt for positive numbers, then introduce the output, before actually asking for any input.

How about something like this:

int main()
{
    const int num = 10;
    int n[num] = { 0 };

    cout << "Welcome to the program. Enter " << num  << " positive numbers: " << endl;
    const float average = medel(n, num);
    cout << "The average of the numbers entered is: " << average << endl;
}

Find a way outside of your program to keep the terminal window open, if it's not already. That's not your program's job.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • I recommend using `cin.ignore`, as in `cin.ignore(100000, '\n')`. This will ignore characters until a newline is entered. – Thomas Matthews May 03 '17 at 17:55
  • 2
    @ThomasMatthews: I don't. There is no need for such tricks here – Lightness Races in Orbit May 03 '17 at 17:56
  • @BoundaryImposition I meant to ask you that, been a long day. – RH6 May 03 '17 at 18:13
  • 1
    @RH6: Okay well as I've said a couple of times, my suggestion is _don't_! I gave some tips in the linked Q&A. – Lightness Races in Orbit May 03 '17 at 18:13
  • 1
    simplest way is to add "pause" to the PROJECT/name PROPERTIES/DEBUGGING Command Arguments in the project and use CTRL + F5 to run the project after it has been compiled. @BoundarImposition is right in pointing out that your program should only do what is it supposed to do ...no more and no less. – Dr t May 03 '17 at 18:26