C++用户输入和错误处理
C++ user entry and 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 退出循环。
感谢您的帮助!
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);
相关文章:
- 错误处理.将系统错误代码映射到泛型
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- posix_spawn():使用posix_scawn()时的错误处理问题
- 在C++中样板"冷/never_inline"错误处理技术的最佳方法是什么?
- 关于 istream 中的错误处理的问题
- 程序使用的 C 库中的错误处理C++
- C++ 错误检查 fstream open() 命令和一般字符串流错误处理
- 使用std::tie进行类似golang的错误处理,同时返回结果,是否有缺点?(C++11)
- Boost进程"系统"功能中的错误处理
- RPN计算器c++错误处理和多个运算符
- 提升精神 x3 错误处理程序与期望
- 构造函数中的错误处理而不会失败
- 当 C++ 中函数参数的输入类型(类)错误时的错误处理
- 关于 ocilib 错误处理的问题,如何使用 ocilib 正确捕获日志错误?
- 我可以使用 std::optional 进行错误处理吗?
- C++ main() 末尾关于错误处理的错误
- 抽象包装带有异常的 C 错误处理的最佳方法
- vwprintf错误处理(ERRNO显示0)
- C++ 使用枚举进行错误处理
- 在 C++ 中创建自己的错误处理机制