I am in a C++ class - looking to use structs for the first time.
Code compiles, runs once through the for loop, the quits after entering the second name. I think it has to so with the string, but not sure. Any insight appreciated. Code follows:
----------
#include <iostream>
#include <string>
using namespace std;
struct student//creates the struct "student" with members name quiz1, quiz2, midterm, and f_exam
{
string name;//the student's name
float quiz1;//the score for quiz 1
float quiz2;//the score for quiz 2
float midterm;//the score for the midterm
float f_exam;//the score for the final
int n = 0;
//Should not compile on standard conforming compiler as aray size is not constant
//Also in your code is is equivalent to student grade7[0];
student grade7[n];
cin>>n;
All operations on that array leads to undefined behavior and buffer overflow.
1 2
cin.clear();
cin.ignore();
Why do you need that here?
I hope you are not trying to input two words as last name?
To elaborate on what MiiNiPaa said, and assuming that your compiler has an extension so that the line compiles, this:
1 2
int n = 0;
student grade7[n];//declares the struct array "student"
Creates an array with zero elements in it. So when you start writing elements into it, you're writing into who-knows-where and get undefined results.
Note that when you do this: cin>>n;
it doesn't change the size of the grade7 array. When you create an array in C++, the expression for the size of the array (n) is evaluated and the compiler creates room for that many elements. If you change n later on, it does not change the size of the array.
Just move the declaration after you set n:
1 2 3
cout<<"How many students are in grade 7 (positive integer only please)?"<<endl;
cin>>n;
student grade7[n];//declares the struct array "student"
To all, thanks for the help. Saw the initialization problem after you guys pointed it out. Worked better, but not perfect, but not because of the initialization problem. Thanks again. Appreciate the help.