A very simple program but I can't figure out why it is wrong...

I was required to write a function to read the input and store it in a array. However, it didn't work. The size will somehow changed to a random number after 2 rounds, and the loop will stopped.

Could anyone point out where I did wrong? I have been trying to slove it for hours...

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <iomanip>

//#include "io.hpp"

using namespace std;

double getExamScoreFromUser();

int main()
{
  int size = 0;
  int selection = 0;
  bool score_entered = false;
  double examScore[] = { 0 };
  do
  {
    cout << "1. Input your exam score" << endl;
    cout << "2. Quit. " << endl;
    
    cout << "Enter your selection: ";
    cin >> selection;
    cin.ignore(1000, 10);

    if (selection > 2)
      cout << "Invalid Input, try again. " << endl;
    else if (selection == 1)
    {
      cout << "How many exams you will enter here:";
      cin >> size;
      cin.ignore(1000, 10);
      for (int i = 0; i < size; i++)
      {
        cout << "Exam " << i << " ";
        examScore[i] = getExamScoreFromUser();//call user to enter scores
      }
    }

  } while (selection != 2);
}

double getExamScoreFromUser()
{
  double score;
  cout << "score is ";
  cin >> score;
  cin.ignore(1000, 10);
  return score;
}


Your exam score array has one element. That means after first round all writes will be done out of bounds. It liiks like one of them corrupted your size variable.

Use vector to solve need for dynamic growth
Thank you for the help!
Yea, I wish I can use vector to solve it but that's too advanced for this class...(I have to show my understanding to the current content...)

I finally figured I should just use

double* getExamScoreFromUser(double* score, int size)

which made things easier... :P

But I also understand what you were saying, I think the requirement said we could set the array a size, which we will have to do a size check to make sure user won't input a size that is too big. I personally don't like static array, so I ignored it...my bad :P

but thanks a lot!
Topic archived. No new replies allowed.