When I compile this code I am unable to enter a list of students' names, which I need to do. There are supposed to be two arrays, one with students' names and one with their scores. I am supposed to output the names of the students who scored above the average. However the problem is that after I input the first student's name, my input/output window (or whatever you call it on Xcode) will not accept another name. Sometimes it will accepts more than one, but this somehow seems to be contingent on the value of the size variable. Any suggestions on how i can get his to work?
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
int size;
cout << "Enter the number of students." << endl;
cin >> size;
int scores[size], i, sum = 0, average;
char names[size];
cout << "Enter each score." << endl;
for (i = 0; i < size; i++)
cin >> scores[size];
cout << "Enter the first name of each student" << endl;
for (i = 0; i < size; i++)
cin >> names[size];
for (i = 0; i < size; i++)
sum += scores[size];
average = sum / size;
for (i = 0; i < size; i++)
{
if (scores[size] > average)
cout << names[size] << endl;
}
return 0;
}
You are using a for-loop...I think you forgot that in your code. Also you have to either use std::string or use dynamically allocated array of char - newchar[size]
int scores[size], i, sum = 0, average;
char names[size];
Unfortunately, in C++, you're not allowed to declare an array like that whose size is determined at runtime. You have a few options on how to fix that:
1) Use std::vector (http://www.cplusplus.com/reference/vector/vector/ ).
2) Allocate the arrays dynamically, using new[] (see http://www.cplusplus.com/doc/tutorial/dynamic/ ).
3) Pick a fixed size (say, 100) for your arrays and don't let the user enter anything more than that.
Also:
12 13
for (i = 0; i < size; i++)
cin >> scores[size];
I think you meant scores[i] here -- scores[size] refers to the element at position size, which is out-of-bounds (array indices go from 0 to size-1).
Same for all of your other for loops.
EDIT: One more thing: char names[size];
Besides the fact that arrays declared like this have to have a size determined at compile time, this actually only declares a single string -- given that you've put #include <string> in your code, you probably meant string instead of char here.