Somehow I could not identify my error in my code. Can someone please help me? Below is the error that cause my problem.
In member function `void student::setRegNo(int*)':
In member function `void student::setRegNo(int*)':
And here is my function
void student::setRegNo (int RegNo[])
{
int length;
int a, b;
for(a=0; a<10; a++){
studentRegNo = RegNo[a];
length=length+1;
}
if (length==10){
for(b=0;b<10;b++)
studentRegNo[b] = RegNo[b];
}
else
cout << RegNo << "out of range" << endl;
return;
}
1) Variable 'studentRegNo' is not declared. It produces compilation error. The way it has been used, it looks like an integer. However, you are overwriting its value 10 times in the first 'for loop'. This gives an impression that it ought to be an array of integer.
2) Variable 'length' is not initialized. It is a logical error. The compiler generally produces an warning in this case.
3) In the second for loop, studentRegNo is being used as an array !!! It was used as an integer in the first 'for loop'.
I am not sure what are you trying to do with this code. Please explain the motive.
Ok, I want to make sure that the RegNo has 10 digits number. Is using an array is the correct way to make sure that it has 10 digits number? Then if it is not, can please tell me what is the correct way to do that?
If you want to store 10 integers into an variable, you need to declare the given variable as an array. You can only use the sub-script operator on arrays. If you initialize the local variables before using them, you should be good to go. Be careful not to give out-of-range indices.
I just try to help you see my code as below:
#include <iostream>
using namespace std;
class student {
public:
void setRegNo(int[]);
private:
int studentRegNo[10];
};
void student::setRegNo (int RegNo[])
{
int length = 0;
int a, b;
for(a=0; a<10; a++){
studentRegNo[a] = RegNo[a];
length=length+1;
}
if (length==10){
for(b=0;b<10;b++)
studentRegNo[b] = RegNo[b];
}
else
cout << RegNo << "out of range" << endl;
return;
}
int main(void)
{
student obj;
int a[] = {1,2,3,4,5,6,7,8,9,0};
thanks! that work well. By the way, if I want to enter manually for the RegNo, do I put it under the main or under the void function? I tend to do the code just like below:
cout << "Enter registration:" << endl;
cin >> RegNo[10]; //however this line does not detect whether 10 digits has been entered or not.
What I mean is, when I enter the registration, it just take any digits whether it is less or more than 10 digits. How can I modify this part?
A sub-script operator is this: [ ]. They're used to access the given element within an array.
Can you give me some example for it?
Certainly.
1 2 3 4 5 6 7 8 9 10
int main( )
{
// Here, we're defining an array with 3 elements, all have been
// initialized with the value zero.
int Array[ 3 ] = { 0 };
// To access an element within the array, we will need to use
// the sub-script operator, like so:
Array[ 0 ] = 10; // Here, we are accessing the first element.
}