How to end a whole program
I have a pretty simple C++ console program. It's working fine, but I have some issues. I have 2 functions. First function called "input" asks from user to input numbers from 6 to 10. In that function I declared:
if ((a[i][j] < 6) || (a[i][j] > 10))
{
cout<<"Invalid input!";
return 0;
}
Second function called "output", prints out those numbers from first function.
In the main it is like:
int main ()
{
...
input (matrix, number);
output (matrix, nubmer开发者_如何学C);
}
My question is this. When I input number that isn't 6-10, my program still do "output" function, so it prints some random numbers. How can I break whole program in exact time when input rules are broken? Without any random output and stuff, just to print "Invalid output", then to start program from the start?
You may check the return value of input()
before calling output()
.
You can use the exit()
function to terminate the program
if(input(matrix,number) != 0) output(matrix,number);
// You don't {} for a single instruction
This should fix your problem.
The usual way to indicate errors is to throw an exception.
int main() {
...
try {
input(matrix, number);
output(matrix, number);
} catch(std::exception& e) {
std::cout << "Error: " << e.what();
}
}
In input:
if ((a[i][j] < 6) || (a[i][j] > 10))
{
throw std::runtime_error("Invalid input!");
}
If your input function return 0 on invalid input and another value on success you can run a loop until your input is valid
...
while(input(matrix,number) == 0);
...
An idiomatic code would be this:
while(input (matrix, number)) //idiomatic loop
{
output (matrix, nubmer);
}
The input()
function should return false
or 0
when the input is invalid, and true
or non-zero, when the input is valid.
The loop above has the same form as we write std::istream
idioms:
std::string word;
while( std::cin >> word )
{
//..
}
//Or
ifstream file;
//...
while( file >> word )
{
//..
}
//Or
while( std::getline(file, word))
{
//..
}
I just explained this idiom here, as to how it works:
- C++ Rewrite a file but leaving out everything before a word
There are plenty of solutions. One is to declare the input
function to return an integer. On success input
can return 0
. On failure (the input is outside the range 6-10) input
returns a negative number (-1
for simplicity). Inside your main function, use a while loop to continue calling input
until it returns 0 for success. Each time input
fails you can print a message telling the client to enter try again. If you want to exit immediately after the first input
failure, you can call exit(1)
inside your main
.
精彩评论