How to work with an array within a do while loop?

I'm working with a much longer code, but shortened it so you would see my problem.

The problem is the

{ while ( NUMbers[0] != 99)
cout << " Program end"; }

portion. I need my do while loop to cease when the user inputs 99 as NUMbers[index]; My professor showed us one day, if I remember right, he created a string variable and set NUMbers equal to it, and used that variable as what 99 was supposed to not equal instead of NUMbers, but I cannot figure out how to do it. And none of the rest of my code will work.


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
#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

int main ()

{

	const char size = 100;
	string NUMbers[size];


	do {

	cout << "Enter A Number: ";
	for (int index = 0; index < size; index++)
	{

		cout << "Enter a Number: ";
		cin >> NUMbers[index];

	}
	
	}

	while ( NUMbers[0] != 99)
		cout << " Program end";


	system ("pause");

	return 0;

}
You really don't want to create a for loop inside your do/while.

You want to use one or the other, not both. Which one depends on how you want to terminate your loop. Do you want to prompt for exactly 100 numbers? If so, use the for loop. Do you want to prompt until the user enters 99? If the later, then use the do/while. With the do/while, you need to add a second condition to make sure you don't overflow the array. See below.

You've got a couple of problems at line 28.
1) You should be comparing NUMbers[index], not NUMbers[0].
2) Since NUMbers is type string, the right side of the comparison must be a quoted string. e.g.
 
while ( NUMbers[index] != "99" && index++ < size)


edit: corrected condition per LB's comment below.
Last edited on
Tried it, I got a compiler error that index was an undeclared identifier.

the loop was supposed to be infinite, just ending when one of the number input was 99.
@AbstractionAnon: that code will access an out-of-bounds index on the last iteration. Consider instead:for(unsigned i= 0; i < size && NUMbers[i] != "99"; ++i)

@AppleDust: You made absolutely no effort to fix the error yourself?

Also, why the use of unsigned char for size? In all the places it is used, it gets promoted to an integer anyway. It makes no sense for it to be of character type.
Last edited on
I got a compiler error that index was an undeclared identifier.
In your original code, index is only defined within the scope of the for statement.


the loop was supposed to be infinite

The loop can't be infinite since you only allocated 100 instances of NUMbers.

LB's suggestion to add && NUMbers[i] != "99" to the termination condition of the for loop addresses both terminating on array full and on user input of 99. This for loop should of course replace your outer while loop.



Topic archived. No new replies allowed.