Stopping the for loop

I cant seem to get a for loop to stop at the last entry. I can stop the user from entering numbers but I can't seem to stop the for loop running all the way to 100. Thank you for any help on this.

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
//enter 100 random numbers.
//Allow the user to stop at anytime
//show the amount of entries
#include<iostream>
#include<string>
using namespace std;
int main() {
	float  n[99];
	int i;
	char t;
	//Instruct the user to enter upto 100 floats and how to stop 
	//for loop to make sure the user stops at 100 entries
	cout << "Enter your values.  Your allowed upto 100 values, 
        press t to stop any time \n";
	for(i=1;i<=99;i++){ 
		cout << "Enter Value: ";
		cin >> n[i];
		cout << "You have " << 100 - i << " entries left \n\n";
		if (n[i] == t)
		break;//This stops the user from being able to enter a value
                //but still totals the i up to 100 and outputs to the screen
	}	
		
	cout << "Number of records: " << i << '\n';//shows how many records entered
	
	return 0;
}
Line 19 is wrong, but you have larger problems.

n[i] is a float, so cin is going to expect you to input something that looks like a float. 't' does not look like a float.

What you need to do is use cin to read a string. Compare the string against "t" and break if equal. Otherwise, you have to convert the string to a floating point number.
In line 10, you are creating a variable t. But you must assign the value of the char so that

char t = 't';

among other things already mentioned.
Thanks for your help. I tried researching "cin to read a string and compare against 't'" but was unsuccessful. I decided to change my variables to
1
2
3
4
5
6
const int size = 99;
using namespace std;
int main() {
	float n[size];
	int i = 1;
	float t = 0;

and just tell the user they cant use 0 as a value and that they need to use 0 to exit. Not exactly what I was looking for, but for what is being asked here it does the trick. I try entering t again to stop it, but for some reason it allows i to continue X times and then stops. X isnt consistent but it doesnt go all the way to 0.

If you have anymore insight into how to use cin to read a string, I would like to read it. thanks again.
Look up getline()

[There are also many many examples of this posted in these forums]
Last edited on
Topic archived. No new replies allowed.