Hi guys, i need some help. (part 1) , i wanted to do a part where if you enter a number bigger than 1000 or smaller den 0 than it will show a output of Invalid input . Try again, Then it will prompt you to key in a new value again. however the code i used does not ask me the question again but just stop there, may i ask why too?
( part 2) , the code shown is the last part of my program, i wanted to make a code whereby after it show the material recommended , it will ask me if i wish to continue arnot, if i do , then it will display the code i show in part1
thanks alot for helping !
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//part1
cout <<"Please enter the ultimate tensile strength (UTS) of material needed ( highest 1000 ): " ;
cin >>strength;
while(!(cin >> strength) || strength < 0 || strength > 1000) //this is the part
{
cout << "Invalid input. Try again: ";
}
//part 2
cout <<"The material that we recommend you to use is"<<material<<"."<<endl<<"Thanks for choosing xxx calculator"<<endl ;
You have two successive cin statements, line 4 and line 6, so program is waiting for another input. Try entering 5 and then 1005 and see what will gonna happen.
This will work:
1 2 3 4 5
while(strength < 0 || strength > 1000) //this is the part
{
cout << "Invalid input. Try again: ";
cin >> strength;
}
Or just remove first cin statement (line 4).
EDIT (part 2)
1 2 3 4 5 6 7 8 9
do {
// ...code...
cout <<"The material that we recommend you to use is"<<material
<<"."<<endl<<"Thanks for choosing xxx calculator"<<endl;
cout << "Continue y/n: ";
char ans;
cin >> ans;
if (ans == 'N' || ans == 'n') break;
} while(true);
there was a red line for the break; part stating break statement can only be used in loop or switch
also , for the last part if the break manage to work , what should i use if i want it to repeat back to the first code i use? like some kind of loop whenever i say yes i wish to continue
You forgot to write do { before cout <<"Please enter... and to put } next to while(true). What we are trying to do here is to create an infinite loop to execute that part of program for infinity but also we want to break that loop if user enters 'N' or 'n'.
Btw you typed cout << "Continue y/n: "; twice.
You might want to exit the program or something like that if access is denied, not to just continue normal execution of it. Returning from main exits the program, so you can use return 0; to accomplish that.
First, please use code tags and format your code, so that it's actually readable.
I don't know exactly what's wrong, but from appearances it seems you're trying to do a do while loop... where you seem to have forgotten to add a do. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
// ...
int main() {
do {
// ...
std::cout << "Continue [YN]? ";
char ans;
std::cin >> ans;
if (ans != 'Y' && ans != 'y')
break;
} while (true);
return 0;
}