C++ 未输入两次

问题描述 投票:0回答:1

enter code here
我正在制作一个可以处理虚数的计算器。当我在终端中运行它时,我可以输入前两个输入,但是第二个输入出现故障。(查看屏幕截图以供参考)这是我的处理程序,其
get_complex_input()
在此部分和复杂文件中运行。

#include <iostream>
using namespace std;
#pragma once

class Complex {
private:
    float real;
    float imaginary;

public:
    Complex() : real(0), imaginary(0) {}

    Complex(float r, float i) : real(r), imaginary(i) {}

    Complex operator+(Complex rhs) {
        return Complex(this->real + rhs.real, this->imaginary + rhs.imaginary);
    }
    Complex operator-(Complex rhs) {
        return Complex(this->real - rhs.real, this->imaginary - rhs.imaginary);
    }
    Complex operator*(const Complex& other) const {
        float new_real = (this->real * other.real) - (this->imaginary * other.imaginary);
        float new_imaginary = (this->real * other.imaginary) + (this->imaginary * other.real);
        return Complex(new_real, new_imaginary);
    }

    Complex operator/(const Complex& other) const {
        float denominator = (other.real * other.real) + (other.imaginary * other.imaginary);
        float new_real = ((this->real * other.real) + (this->imaginary * other.imaginary)) / denominator;
        float new_imaginary = ((this->imaginary * other.real) - (this->real * other.imaginary)) / denominator;
        return Complex(new_real, new_imaginary);
    }

    // Function to find the conjugate of a complex number
    Complex conjugate() {
        return Complex(this->real, -(this->imaginary));
    }

    // A helper function to print the complex number
    void print() const {
        if (imaginary >= 0)
            cout << real << " + " << imaginary << "i" << endl;
        else
            cout << real << " - " << -imaginary << "i" << endl;
    }
};
#include <iostream>
#include "Complex.h"
#pragma once
using namespace std;

class Handler {
public:
    // Function to display the menu and get the user's choice
    static int print_and_get_choices() {
        int choice;
        cout << "Complex Numbers Calculator" << endl;
        cout << "1. Add two complex numbers" << endl;
        cout << "2. Subtract two complex numbers" << endl;
        cout << "3. Multiply two complex numbers" << endl;
        cout << "4. Divide two complex numbers" << endl;
        cout << "5. Find the conjugate of a complex number" << endl;
        cout << "6. Exit" << endl;
        cout << "Enter your choice: ";
        cin >> choice;
        return choice;
    }

    // Function to add two complex numbers
    static void add_two_complex_numbers() {
        Complex num1 = get_complex_input();
        Complex num2 = get_complex_input();
        Complex result = num1 + num2;
        cout << "Result of addition: ";
        result.print();
    }

    // Function to subtract two complex numbers
    static void subtract_two_complex_numbers() {
        Complex num1 = get_complex_input();
        Complex num2 = get_complex_input();
        Complex result = num1 - num2;
        cout << "Result of subtraction: ";
        result.print();
    }

    // Function to multiply two complex numbers
    static void multiply_two_complex_numbers() {
        Complex num1 = get_complex_input();
        Complex num2 = get_complex_input();
        Complex result = num1 * num2;
        cout << "Result of multiplication: ";
        result.print();
    }

    // Function to divide two complex numbers
    static void divide_two_complex_numbers() {
        Complex num1 = get_complex_input();
        Complex num2 = get_complex_input();
        Complex result = num1 / num2;
        cout << "Result of division: ";
        result.print();
    }

    // Function to find the conjugate of a complex number
    static void find_conjugate_of_a_complex_number() {
        Complex num = get_complex_input();
        Complex result = num.conjugate();
        cout << "Conjugate: ";
        result.print();
    }

private:
    // Helper function to get user input for a complex number
    static Complex get_complex_input() {
        float real, imaginary;
        cout << "Enter the real part: ";
        cin >> real;
        cout << "Enter the imaginary part: ";
        cin >> imaginary;
        return Complex(real, imaginary);
    }
};

我只想让输入能够检查我的功能。另外,如果这意味着什么,请在文件夹终端上使用 ./a.out

c++ input
1个回答
0
投票

显示试运行的屏幕截图丢失。但是,您很可能在复数的虚部之后输入

i

例如,假设您要添加

1+2.5i
2-5i

第一个复数将被正确输入,但是当您的程序尝试输入第二个复数的实部时,它将失败。发生这种情况是因为字符

i
保留在第一个复数的输入流中。

这是我在我的系统上尝试你的程序时发生的情况:

Enter the real part: 1
Enter the imaginary part: 2.5i     <-------- 2.5 inputs okay, but `i` remains unread
Enter the real part: Enter the imaginary part: Result of addition: 1 - 1.07374e+08i

cin >> real
看到角色
i
时,它会失败,并将
std::cin
置于失败状态。之后,所有带有
std::cin
的后续输入都将失败。您可以在上面的示例中看到,尝试输入第二个数字的虚部失败。

一个简单的解决方法/修复方法是仅输入数字。请勿在虚部后输入

i
。否则,您可以要求用户输入
i
,但如果这样做,您将需要将
i
输入到
char
类型的变量中。

char ch{};
float real, imaginary;
std::cout << "Enter the real part: ";
std::cin >> real;
std::cout << "Enter the imaginary part: ";
std::cin >> imaginary;
std::cin.get(ch);  // No whitespace is allowed before the character `i`.
if (ch != 'i') { /* error */ }

无论您是否允许用户输入

i
,您可能希望使用控制台输入的专用功能。

强大的输入例程

每当我希望用户输入数字时,我通常都会调用一个函数。这样,我可以捕获无效条目,并让用户重试。

函数

get_float
(如下)是一个示例。

class Handler {
    // ...
private:
    // Dedicated funtion to input a `float`.
    static float get_float(std::string const& prompt) {
        for (;;) {
            std::cout << prompt;
            if (float n{}; !(std::cin >> n)) {
                std::cout << "Invalid entry. Please reenter.\n\n";
                std::cin.clear();
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            }
            else {
                return n;
            }
        }
    }

    // Helper function to get user input for a complex number
    static Complex get_complex_input() {
        float real{ get_float("Enter the real part: ") };
        float imaginary{ get_float("Enter the imaginary part: ") };
        return Complex(real, imaginary);
    }
};

get_float
检测到故障时,它会通过调用
std::cin
std::cin.clear()
恢复到“良好”状态。然后,它通过调用
std::cin.ignore
丢弃仍在流中的字符。

这是我将

get_float
添加到 OP 中的程序时发生的情况:

Enter the real part: 1
Enter the imaginary part: 2.5i      <----- Whoops. I entered `i`.
Enter the real part: Invalid entry. Please reenter.

Enter the real part: 2
Enter the imaginary part: -5        <----- No `i` this time.
Result of addition: 3 - 2.5i

整数输入专用函数

函数

get_int
(如下)与
get_float
类似,不同之处在于它添加了一个功能,允许您指定可接受的值范围。

get_int
可用于收紧您的菜单系统。

class Handler {
    static int print_and_get_choices() {
        std::cout << 
            "Complex Numbers Calculator" 
            "\n"
            "\n 1. Add two complex numbers"
            "\n 2. Subtract two complex numbers"
            "\n 3. Multiply two complex numbers"
            "\n 4. Divide two complex numbers"
            "\n 5. Find the conjugate of a complex number"
            "\n 6. Exit"
            "\n\n";
        int const choice{ get_int("Enter your choice: ", 1, 6) };
        std::cout << '\n';
        return choice;
    }
    // ...
private:
    // Dedicated funtion to input an `int`.
    static int get_int(
        std::string const& prompt,
        int const min,
        int const max)
    {
        for (;;) {
            std::cout << prompt;
            if (int n{}; !(std::cin >> n)) {
                std::cout << "Invalid entry. Please reenter.\n\n";
                std::cin.clear();
                std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            }
            else if (n < min || n > max) {
                std::cout << "Invalid entry. Please reenter.\n"
                    << "Entries must be between " << min << " and " << max << ".\n\n";
            }
            else {
                return n;
            }
        }
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.