English 中文(简体)
我怎么能够证实用户进入价值(int)而不是与进入钥匙[复制]同步。
原标题:How can I validate that an user enter a value (int) instead of skip with the enter key [duplicate]
  • 时间:2024-02-23 18:11:01
  •  标签:
  • c++

当我敦促进入钥匙而没有进入其他价值时,情况就没有发生,就像冻结该方案一样,在我进入无价值之前,再没有再过。 我如何确定这一点?

#include <iostream>
#include <limits>
#include <iomanip>

using namespace std;

void menu(int option)

int main(){
    int op{0};

    do{
        cout << setw(20) << "BMI Calculator" << endl;
        cout << "1. Personal Information" << endl;
        cout << "2. Physical Information" << endl;
        cout << "3. Calculate BMI" << endl;
        cout << "4. Result" << endl;
        cout << "5. Exit" << endl;


        cin >> op;

        if (cin.good()){
            menu(op);
        }
        else{
            cout << "Invalid input" << endl;
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(),  
 );
        }

    } while (op != 5);

    return 0;
}

I expect that when I don t enter any value in cin >> op; the program gets into de else statement and then start the loop again printing the options. Instead of that the loop is kind of freezed until I enter a number.

感谢gu, 我感谢你们的一切帮助!

问题回答

我如何能够证实用户进入价值(int)而不是与进入关键阶段的跳跃。

The trick is to use 改为<代码>:string。

std::string s;
std::getline(std::cin, s);
if (s.empty()) {
    // error...
}

<代码>getline 摘自投入流的特性,并抄录。 上述超载有两个参数。

  1. The first is a reference to an input stream. This is the stream getline reads from.
  2. 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...




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签