Apr 9, 2013 at 2:35am UTC
I have a function with an if and else statement inside a for loop but both the if and else are both executing.
What am I doing working?
Thank You.
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
int removeStudent( int Iarray[], double dArray[], string sArray[], int removeID,
string &name, double &grade, int &size )
{
int index;
char done;
cout << endl;
cout << "Enter remove student ID number : " ;
cin >> removeID;
for ( index = 0; index < size; index++ )
{
if ( removeID == Iarray[index] )
{
cout << "Present Student Name : " <<
sArray[index] << endl;
cout << "Present Student Grade : " <<
dArray[index] << endl;
cout << endl << endl;
cout << "Complete student editing process <y/n>: " ;
cin >> done;
if ( toUpperCaseLetter(done) == 'Y' )
{
Iarray[index] = '\0' ;
sArray[index] = '\0' ;
dArray[index] = '\0' ;
}
}
else
{
cout << endl;
cout << "ERROR: Student ID not found, Remove Student Module aborted" << endl;
cout << endl;
}
}
}
Last edited on Apr 9, 2013 at 5:39pm UTC
Apr 9, 2013 at 2:44am UTC
I don't think your else statement is part of an if statement.
Apr 9, 2013 at 2:51am UTC
@buffbill How?
It looks like
1 2 3 4 5 6 7 8 9
if (...)
{
if (...)
{
}
}
else
{
}
Last edited on Apr 9, 2013 at 2:53am UTC
Apr 9, 2013 at 2:57am UTC
That indentation needs a bit of work. Have you tried stepping through with a debugger to see what's happening?
Apr 9, 2013 at 2:59am UTC
Debugger? I am pretty new to c++. This function is for a class assignment.
Apr 9, 2013 at 3:33am UTC
Let me ask again: What makes you think both branches are executing?
Apr 9, 2013 at 3:45am UTC
@ L B I guess if the remove id is in the array then it does something
else it shows error
I don't think it's that complicated.
Last edited on Apr 9, 2013 at 3:45am UTC
Apr 9, 2013 at 4:30am UTC
He's probably seeing the output from the 'if' branch in one iteration of the for loop followed by the output from the 'else' branch in the next iteration. This could make it appear that both branches are executing.
@JazzyJeff. If you don't want to use a debugger, just output the value of index in each branch. The values would be the same if both the 'if' and the 'else' really are (somehow) executing.
Last edited on Apr 9, 2013 at 4:33am UTC
Apr 9, 2013 at 7:18am UTC
Seriously, this kind of indentation is terrible. I mean, I've seen people use 8 spaces indents, 4-space indents and even 2-space indents. But using 1-space dual-indent per nesting level... OMG.
Apr 9, 2013 at 7:17pm UTC
It was simple. I set the function to a Boolean.