idk how to accept 5 numbers in one line, and assign them to a variable. can you explain please?
1 2 3 4
//ask student for 5 test grades they should all be entered into one line, with spaces.
cout<<"Insert 5 test grades."<<endl;
int tests[5]={}; //for user inputting grades
cin>>tests[0,1,2,3,4]; //for user inputting grades
The for loop is correct, but there is no explicit need to use a vector instead of an array. If you do use a vector, though, make sure you resize() it to have enough elements before trying to assign values.
You could also just have each element of your array in a single seried cin:
You don't need a vector at all. If you are dealing with arrays than you more than likely don't know anything about vectors yet. Though it doesn't really matter which you use, its up to the programmers preference, you can still achieve what you are trying to accomplish depending on what kind of programming environment you are coding in (Visual Studios, PuTTy, etc). If you are coding in anything that supports C++11 which I imagine you are, consider this approach for easier readability. Of course if you know the size of your array to start out with you can easily just do something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
//Since we know how many grades the user is going to put in (5)
//We can just loop through until the user has entered 5 entries.
//To accomplish this, we start at 0 and increment 5 times, does that make sense?
//Remember all arrays start at position 0, not position 1!
//0 1 2 3 4 are the positions in our array, which means that 4 is the last position.
//Think of positions of an array as n
//The last position of the last element in an array is always going to be (n-1).
//Does that make sense?
//For Example, the last position of an array of 100 elements is going to be (100 - 1) which is
//position 99.
int userInput;
for(int i = 0; i < 5; i++)
{
//Talk to the user
cout << "Insert 5 grades: "; cin >> userInput;
//Store the input they gave you in your array!
testGradesArray[i] = userInput;
}
Or alternatively, if you don't want to think about how many elements are in an array you can just use the size() built in function from the built in array class in C++
#include<iostream>
#include<array>
usingnamespace std;
int main()
{
//int is the data type and 5 is the # of elements in your array.
array<int, 5> testGradesArray;
int userInput;
for (int i = 0; i < testGradesArray.size(); i++)
{
cout << "Insert 5 test grades: "; cin >> userInput;
testGradesArray[i] = userInput;
cout << "\nSuccess! You have entered " << (i + 1) << " grade(s) " << endl;
}
cout << "Complete!" << endl;
cout << "\n The grades you have entered are: ";
for (int i = 0; i < testGradesArray.size(); i++)
{
cout << testGradesArray[i] << " ";
}
cout << endl;
cout << "\n Program Complete!" << endl;
system("pause");
}