I am having trouble debugging this code so it reads two columns from the file and when the first column (Department is the same it just adds the second column to the old dept already created)This code is having trouble with looping. The output should be a partially filled array with only few departments. Any walk through, help would be much appreciated ! Thanks.
Consider what happens when you DO find the department. At line 31, you increment candy[index]. Then when you exit the loop, you still execute the code to add the department as though you DIDN'T find the department.
To fix this, (1) make index a local variable within main (right now it's local to the for loop. (2) Add a breakstatement after line 31 Then put lines 36-38 inside if (index == valuecounter) {
The break statement ensures that the loop will exit when it finds the department. The new "if" statement really says "if I didn't find the department...."
hello! thank you for fast response! so I did as you suggested and I actually understand the process! but the code seems to be off a little still. When I try to run it it only adds and shows dept 910 27. It looks like other departments are skipped.
In future please edit your posts to modify the code, add the code to a new post. When you alter the code it makes following the topic harder.
Instead of using index and valuecounter in the if() statement after the loop I recommend using a flag variable instead.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
...
while (inputFile >> Department >> Candy)
{
bool found = false;
// Update previous values
for (int index = 0; index < valuecounter; index++)
{
if (dept[index] == Department)
{
candy[index] += Candy;
found = true;
break;
}
}
if (!found)
...