如何修复损坏的输入流

时间:2018-12-11 08:28:32

标签: c++ io

我编写了一个程序,只是发现输入流“中断”。为了参考(或其他目的),下面是代码:

#include <iostream>
#include "../include/number_comparison_lib.h"

int main() {

    std::string unit_indicator = "default";
    double temp1 = 0;
    double temp2 = 0;
    double temp_smallest_value = 0; //used to store the smallest value
    double temp_biggest_value = 0; //used to store the biggest value
    int values_equal = 1; //used to store whether the values are equal (true or false)

    std::cout << "\nEnter as many numbers as you like. " << std::endl;
    std::cin >> temp2;
    temp_smallest_value = temp2; //kickstart the variable so that it will not stay as 0 and affect the comparison
    temp_biggest_value = temp2; //just in case the first value is the biggest value

    double temp_val = temp2; //store the first value
    while (std::cin >> temp1) { //cannot use both temp1 and temp2 since the input will need to be even, which is unflexible
        temp_smallest_value = find_min(temp_smallest_value, temp1); 
        temp_biggest_value = find_max(temp_biggest_value, temp1); 

        //as long as values_equal is still 1 , keep comparing
        //if it's 0 or 2, it means one of the comparisons returns 0, therefore stop comparing 
        if (values_equal == 1) {
            values_equal = determine_equal(temp_val, temp1, true); //compare previous value to current value, and specify to enable almost-equal
            temp_val = temp1; //assign current value
        }
    }

    //output the final values
    std::cout << "\nLargest value: " << temp_biggest_value << '\n' << "Smallest value: " << temp_smallest_value << std::endl; 

    switch(values_equal) {
        case 1:
            std::cout << "The values are equal." << std::endl;
            break;
        case 0:
            std::cout << "The values are not equal." << std::endl;
            break;
        case 2:
            std::cout << "The values are almost equal." << std::endl;
            break;
        default:
            std::cout << "ERROR: This message was not supposed to show up. Try again." << std::endl;
            break;
    }

     std::cin >> unit_indicator;
     std::cout << unit_indicator;

     return 0;
}

类似于我的最后一个问题,代码跳转到末尾而没有接收或打印输入。 (就像std::cin >> unit_indicatorstd::cout >> unit_indicator这两行根本不在那儿一样)。我已经看过this question,但似乎没有帮助。我也尝试过

clear(std::ios_base::goodbit);

在最后一行之后,尽管我不确定我是否做对了。 (https://en.cppreference.com/w/cpp/io/basic_ios/clear

我也没有运气使用过ignore(std::numeric_limits<std::streamsize>::max())。这里一定有我想念的东西。请帮忙。

(我使用|结束了输入流,而不是CTRL + D结束了,据我所知,输入流不会在那里“中断”。)

编辑:std::cin.clear()也不清除流,我对其进行了测试,将其放在std::cin >> unit_indicator后面,没有任何运气。

编辑:我不确定使用std::cin.clear()std::cin.ignore()来修复它。还是谢谢你。

0 个答案:

没有答案