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.
//enter 100 random numbers.
//Allow the user to stop at anytime
//show the amount of entries
#include<iostream>
#include<string>
usingnamespace 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;
}
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.
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
constint size = 99;
usingnamespace 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.