C ++用户输入和错误处理

时间:2014-02-17 03:10:38

标签: c++ error-handling

我目前正在编写一个骑士旅行计划,我正在考虑处理我遇到的问题的最佳方法。我的目标是提示用户在电路板上输入几个输入作为起始位置。这意味着用户需要能够输入多个数字,在我看来,这意味着我需要一个可以接受输入的空数组。我用C ++编写代码,这是我到目前为止所做的:

#include <iostream>
#include <iomanip>
using namespace std;

int greeting(){

cout << "Welcome to the Knights Tour! Please, enter your desired starting places." <<
endl << "Enter any numbers 1-64, and type -1 to start." << endl << endl;


int board[8][8] = {{1,2,3,4,5,6,7,8},
                {9,10,11,12,13,14,15,16},
                {17,18,19,20,21,22,23,24},
                {25,26,27,28,29,30,31,32},
                {33,34,35,36,37,38,39,40},
                {41,42,43,44,45,46,47,48},
                {49,50,51,52,53,54,55,56},
                {57,58,59,60,61,62,63,64}
                };

for (int row = 0; row < 8; row++){

        for(int column=0; column<8; column++){
            cout << setw(3) << board[row][column] << " ";
        }
        cout << endl;
}
cout << endl;

}

int main(){
greeting();
}

我已经尝试了几种接受用户输入的方法,但我最终要做的是只允许1-64的整数输入并允许用户输入-1以退出循环。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

int position = 0;
std::string line;
do
{
    while (std::cout << "Select position 1-64, or type -1 to exit\n" &&
           std::getline(std::cin, line))
    {
        std::istringstream iss(line);
        position = 0;
        if (iss >> position &&
            (position == -1 ||
             position 1 <= position && position <= 64))
        {
            char c;
            if (!(iss >> c))
                break;
            std::cerr << "trailing character also found on input line, please try again\n";
        }
        else
            std::cerr << "you entered an invalid position, please try again\n";
    }
    if (1 <= position && position <= 64)
    {
        // do/call your position-related work here...
    }
} while (position != -1 && std::cin);