要从外壳程序接收一个介于(0,8)间隔内的整数值,请执行以下操作:I cin
到数组的uint8_t
元素,
char answer;
do
{
// Instructions
std::cout << "Linear actuator resolution is:\n"
<< "\u0394x = \u03B1r/2^i, with \u03B1 = " << std::to_string(ALPHA)
<< " degrees, r = " << std::to_string(pulleyR) << " m and i in [0 : 8]\n";
// Parameter selection
std::cout << "Please enter a valid value for param 'i': ";
std::cin >> Engines_uSteppingLevel[RAIL];
if(Engines_uSteppingLevel[RAIL] > (RES_LEVELS - 1))
// Wrong selection, repeat question
std::cout << '\r';
else
{
// Print out the selected resolution and ask user to confirm or restart selection
std::cout << "Selected linear resolution: " << std::fixed << std::setprecision(4)
<< ALPHA*pulleyR/(1<<Engines_uSteppingLevel[RAIL])
<< "m, enter 'y' to confirm, any other key to change selection ";
std::cin >> answer;
if(answer == 'y')
break;
}
}while(true);
即使输入正确的值,循环也不会中断。
输入:
std::cout << Engines_uSteppingLevel[RAIL] << ' ' << (RES_LEVELS - 1) << '\n';
代替:
std::cout << '\r';
shell输出为:
Please enter a valid value for param 'i': 0
0 8
Please enter a valid value for param 'i': 3
3 8
这没有意义。
答案 0 :(得分:1)
您在这里遇到的问题是C ++处理uint8_t类型的方式:它认为这是一个字符。如果将调试输出语句更改为:
std::cout << static_cast<int>(Engines_uSteppingLevel[RAIL]) << ' ' << (RES_LEVELS - 1) << '\n';
您将看到,当您输入'0'时,并且uint8_t变量中存储了ASCII'0',该变量的值为48。类似地,当您键入'3'时,您存储的是51,依此类推。
最适合您的解决方案是使用字符转换,如下所示:
Engines_uSteppingLevel[RAIL] -= '0';
请注意,此解决方案仅适用于个位数的值。一个更健壮,可扩展的解决方案将涉及std :: string或char缓冲区,然后调用atoi,strtoul,std :: stoul或类似的东西。