我如何能够证实用户进入价值(int)而不是与进入关键阶段的跳跃。
The trick is to use 改为<代码>:string。
std::string s;
std::getline(std::cin, s);
if (s.empty()) {
// error...
}
<代码>getline 摘自投入流的特性,并抄录。 上述超载有两个参数。
- The first is a reference to an input stream. This is the stream
getline
reads from.
- The second is a reference to a
std::string
. This is the string getline
copies to.
When an newline character (
) is encountered, getline
stops extracting characters, and the newline is extracted and discarded (without appending it to the string).
<代码>getline 回归输入-流参考(即其第一参数)。 可检测到<代码>getline。 某些方面失败(通常是因为在文件结尾处以投入渠道援引)。
在getline
之后,您可使用插图启动istringstream
,然后从中提取编号。
std::istringstream iss{ s };
int value{};
if (!(iss >> value) {
// error...
}
一种比较复杂的办法对<代码>编码>编码代码>进行核对,以确保数字只带白色空间。 诸如<代码>1×等内容被否决。
这种方法使用I/O 操纵器std:ws
读取的白色空间,然后检查:istringstream
处于最后备案(即它不属于特性)。
std::istringstream iss{ s };
int value{};
if ((iss >> value) && !iss.eof())
iss >> std::ws;
if (iss.fail() || !iss.eof()) {
// error...
}
如何运行<代码>get_int 著作如下。
A function to input an integer from the keyboard
大多数方案管理员的职能与职能<代码>get_int(以下)相似,他们用来从关键板上输入一个分类账。 <代码>get_int将投入和验证结合起来,直至有效输入。 由于它围绕<条码>、目标线条码>建造,它将锁定空白线,并拒绝其无效。
min和max
允许打电话者具体说明有效条目的范围。
- When parameter
min
is omitted, it defaults to std::numeric_limits<int>::min()
, which effectively means there is no lower limit.
- Similarly, when parameter
max
is omitted, it defaults to std::numeric_limits<int>::max()
, which means there is no upper limit.
- When an entry is out of range, a carefully crafted error message mentions
min
and max
only when they are different from their default values.
- Parameters
ist
and ost
, respectively, default to std::cin
and std::cout
. It is useful to have them as parameters in case you want to use other streams during testing.
#pragma once
// console_io.h
// Functions used for keyboard I/O:
// - get_int
// - get_double
// - get_yes_no
// - press_enter_to_continue
// - etc.
#include <iostream>
#include <limits>
#include <string>
int get_int(
std::string const& prompt,
int const min = std::numeric_limits<int>::min(),
int const max = std::numeric_limits<int>::max(),
std::istream& ist = std::cin,
std::ostream& ost = std::cout);
// end file: console_io.h
// console_io.cpp
// Functions used for keyboard I/O:
// - get_int
// - get_double
// - get_yes_no
// - press_enter_to_continue
// - etc.
#include <format>
#include <iomanip>
#include <iostream>
#include <limits>
#include <sstream>
#include <stdexcept>
#include <string>
#include "console_io.h"
int get_int(
std::string const& prompt,
int const min,
int const max,
std::istream& ist,
std::ostream& ost)
{
int n;
for (;;)
{
ost << prompt;
std::string s;
if (!std::getline(ist, s))
throw std::runtime_error("get_int: `std::getline` failed unexpectedly.");
if (s.empty())
{
ost << "Invalid entry. Please reenter.
"
"Blank lines are not allowed.
";
continue;
}
std::istringstream iss{ s };
if ((iss >> n) && !iss.eof())
iss >> std::ws;
if (iss.fail() || !iss.eof())
{
ost << "Invalid entry: " << std::quoted(s) << ". Please reenter.
";
}
else if (n < min || n > max)
{
ost << std::format("Invalid entry: {}. Please reenter.
", n);
if (min > std::numeric_limits<int>::min() &&
max < std::numeric_limits<int>::max())
ost << std::format("Entries must be integers between {} and {}.
", min, max);
else if (min > std::numeric_limits<int>::min())
ost << std::format("Entries must not be less than {}.
", min);
else if (max < std::numeric_limits<int>::max())
ost << std::format("Entries must not be greater than {}.
", max);
}
else
{
break;
}
}
return n;
}
// end file: console_io.cpp
Each menu option is a function call
此处是使用<代码>get_int执行《巴厘岛行动计划》时使用的模拟方案。
std:unreachable(
>)是C++23的特征,使您能够向汇编者确定一个方案中那些无法设计的部分。 See CppReference for more info。
// main.cpp
#include <iostream>
#include <string>
#include "console_io.h"
void personal_information() {
std::cout << "Under construction...
";
}
void physical_information() {
std::cout << "Under construction...
";
}
void calculate_BMI() {
std::cout << "Under construction...
";
}
void display_result() {
std::cout << "Under construction...
";
}
void main_menu()
{
const char* const menu
{
"BMI Calculator"
"
1. Personal Information"
"
2. Physical Information"
"
3. Calculate BMI"
"
4. Result"
"
5. Exit"
"
"
};
enum { PersonalInformation = 1, PhysicalInformation, CalculateBMI, Result, Exit };
for (;;)
{
std::cout << menu;
int op{ get_int("Choice? ", 1, 5) };
std::cout <<
;
switch (op)
{
case PersonalInformation:
personal_information();
break;
case PhysicalInformation:
physical_information();
break;
case CalculateBMI:
calculate_BMI();
break;
case Result:
display_result();
break;
case Exit:
std::cout << "Exiting...
";
return;
default:
std::unreachable();
}
}
std::unreachable();
}
int main()
{
main_menu();
}
// end file: main.cpp
Output from a sample run
注意发现并标明空白输入线。
BMI Calculator
1. Personal Information
2. Physical Information
3. Calculate BMI
4. Result
5. Exit
Choice?
Invalid entry. Please reenter.
Blank lines are not allowed.
Choice? 5
Exiting...