【问题标题】:Error handling with c++使用 C++ 处理错误
【发布时间】:2016-10-17 13:20:13
【问题描述】:

我需要在 C++ 中进行一些错误处理,以纠正用户输入(如果它是字母或字符串)。我需要使用 .at()、.length() 和 atoi 来处理这个问题。我不确定如何/在哪里实施这些是问题所在。

#include <iostream>
#include <stdlib.h>
#include <string>
#include <time.h>

using namespace std;

int main() {


    srand(time(0));
    int number;
    number = rand() % 50 + 1;
    int guess;
    int x;


    for (x = 5; x > 0; x--) {
        cout << "Guess my number, it's between 0-50. You have 5 guesses: ";
        cin >> guess;
        if (guess < number){
            cout << "Your guess was too low" << endl;
        }
        else if (guess > number){
            cout << "You guess was too high" << endl;
        }
        else {
            cout << "You're exactly right!" << endl;
        break;
    }
}   while (guess != number){
    break;
}




return 0;

}

【问题讨论】:

  • 如果你试图捕捉用户输入的错误,那么将你的错误捕捉代码放在你得到用户输入的地方。至于方法,我很确定你已经能够检查一个数字是否小于 0。
  • int 猜测; cin >> 猜测;那么 - 如果用户输入一个字母,你认为会发生什么?

标签: c++ string error-handling


【解决方案1】:

输入验证的最佳方法是编写一个读入std::string 的函数,检查所需内容,并仅在通过测试时返回一个值:

int get_value() {
    std::string input;
    int value = -1;
    while (value < 0) {
        std::cout << "Gimme a value: ";
        std::getline(std::cin, input);
        try {
            value = std::stoi(input);
        } catch(...) {
            value = -1;
        }
    }
    return value;
}

【讨论】:

  • “写一个函数”:+1 新程序员的错误就是写神函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
  • 2014-05-11
  • 2011-11-19
  • 2013-08-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多