当用户输入字符串而不是int时,C ++中的异常处理

时间:2017-06-02 10:14:11

标签: c++

我有一个程序,要求用户输入一个整数,然后必须转到几个条件。当我运行该程序时,如果我输入int号码它可以工作,但如果我输入一个字符,程序只会发送错误消息。 我认为异常处理可能在这里工作,但我不知道该怎么办。帮助你们!

这是我的编程的一部分:

#include <iostream.h>
#include <conio.h>
int i, j, data;
void main()
{
 int tempdata;
 retry:
 cout<<"\n\n Enter the row and coloumn where you want to enter data"   <<endl;
 cin>>i>>j;
 if (i>=1 && i<=9 && j>=1 && j<=9)
 {
   cout<<"\n Enter your desired value to put in that place"<<endl;
   cin>>tempdata;
    if(tempdata>=1 && tempdata<=9)
    {
      data=tempdata;
    }
    else
    {
      cout<<"\n Soduku contains numbers from 1 to 9 only.Please try again"<<endl;
      goto retry;
    }
 }
 else
 {
    cout<<"\nEntered row or coloumn is not valid"<<endl;
    cout<<"Please try again"<<endl;
    goto retry;
 }
  getch();
 } 

2 个答案:

答案 0 :(得分:2)

您应该使用异常处理,而不是cout。

if(tempdata>=1 && tempdata<=9)
{
  data=tempdata;
}
else
{
  throw std::runtime_error("Soduku contains numbers from 1 to 9 only.Please try again");
}

通过将所有这些放入函数而不是main函数中,然后可以在try / catch块中调用此函数,并正确处理异常:如果您有GUI,则显示弹出消息,忽略输入等。重要的是,如果忽略它,它实际上不会被忽略。它被处理。这使您的代码更加清洁和可维护。例如:

try
{
    input();
}
catch(std::runtime_error& e)
{
    // deal with your invalid input here
}

此外,goto语句被认为是不好的做法。可以使用if / else或while语句或函数中的返回代码轻松替换它们。使用它们往往会使代码难以理解,难以理解。

答案 1 :(得分:0)

您需要验证cin >>是否成功,然后才能使用输入的值。如果用户输入的数据与预期类型不匹配,则必须先清除错误,然后才能再次读取新输入。

试试这个:

#include <iostream>
#include <limits>

int i, j, data;

bool isNumValid(int data) {
    return ((data >= 1) && (data <= 9));
}

void clearInput() {
    std::cin.clear();
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}

int main() {
    int tempdata;

    do {
        std::cout << "\n\n Enter the row and column where you want to enter data" << std::endl;

        if (!(std::cin >> i >> j)) {
            std::cout  << "\n Please enter numbers only!" << std::endl;
            clearInput();
            continue;
        }

        if (!isNumValid(i) || !isNumValid(j)) {
            std::cout << "\nEntered row or column is not valid" << std::endl;
            std::cout << "Please try again" << std::endl;
            continue;
        }

        std::cout << "\n Enter your desired value to put in that place" << std::endl;
        if (!(std::cin >> tempdata)) {
            std::cout  << "\n Please enter a number only!" << std::endl;
            clearInput();
            continue;
        }

        if (!isNumValid(tempdata) {
            std::cout << "\n Soduku contains numbers from 1 to 9 only" << std::endl;
            std::cout << "Please try again" << std::endl;
            continue;
        }

        data = tempdata;
    }
    while (true);

    std::cin.get();
    return 0;
}

可替换地:

#include <iostream>
#include <limits>
#include <stdexcept>

int i, j, data;

bool isNumValid(int data) {
    return ((data >= 1) && (data <= 9));
}

void checkRowColValid(int row, not col) {
    if (!isNumValid(row) || !isNumValid(col))
        throw std::out_of_range("Entered row or column is not valid");
}

void checkDataValid(int data) {
    if (!isNumValid(data))
        throw std::out_of_range("Soduku contains numbers from 1 to 9 only");
}

int main() {
    int tempdata;

    std::cin.exceptions(std::ios_base::failbit);

    do {
        try  {
            std::cout << "\n\n Enter the row and column where you want to enter data" << std::endl;

            std::cin >> i >> j;    
            checkRowColValid(i, j);

            std::cout << "\n Enter your desired value to put in that place" << std::endl;

            std::cin >> tempdata;
            checkDataValid(tempdata);

            data = tempdata;
        }
        catch (const std::out_of_range &e) {
            std::cout << "\n " << e.what() << std::endl;
            std::cout << "Please try again" << std::endl;
        }
        catch (const std::ios_base::failure &) {
            std::cout  << "\n Please enter numbers only!" << std::endl;
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }
    while (true);

    std::cin.get();
    return 0;
}