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

C++ user entry and error handling

本文关键字:错误 处理 输入 用户 C++      更新时间:2023-10-16

我目前正在编写一个骑士之旅计划,我正在尝试思考处理我遇到的问题的最佳方法。 我的目标是提示用户输入多个输入,以便在板上开始。 这意味着用户需要能够输入几个数字,在我看来,这意味着我需要一个可以接受输入的空数组。 我正在用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 退出循环。

感谢您的帮助!

int position = 0;
std::string line;
do
{
    while (std::cout << "Select position 1-64, or type -1 to exitn" &&
           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 againn";
        }
        else
            std::cerr << "you entered an invalid position, please try againn";
    }
    if (1 <= position && position <= 64)
    {
        // do/call your position-related work here...
    }
} while (position != -1 && std::cin);