lundi 11 février 2019

Need explanation of behaviour of std::cin in this very simple program

I was resolving some exercises to pass the time and I encountered something I don't understand, I am going to explain:

What the program does: "Write a program that reads and stores a series of integers and then computes the sum of the first N integers. First ask for N, then read the values into a vector, then calculate the sum of the first N values" Since I asked for N as the second step:

In the second std::cin (std::cin >> values_to_compute) it has to leave the while statement to continue the program, "only possible if" what is read is not a double. So I can type, for example; 'k' or "how are you?" or Ctrl + Z (I am on Windows 10).

int main() {
    try {
        double holder {0};
        std::vector<double> values;
        while (std::cin >> holder) {
            values.push_back(holder);
        }
        std::cin.clear();
        std::cout << "Out of the loop, now entering to the other std::cin\n";
        int values_to_compute {0};
        std::cin >> values_to_compute;
        std::cout << "Computing...\n";
        double result_computed {0};
        for (int i {0}; i < values_to_compute; ++i) {
            result_computed += values[i];
        }
        std::cout << "Result computed " << result_computed << '\n';

        system("pause");
        return 0;
    }
    catch (std::runtime_error& e) {
        std::cerr << e.what() << '\n';

        system("pause");
        return 1;
    }
}

Ok, so? So... std::cin leaves the while in a not good() state. I have to call std::cin.clear() to use std::cin again. Ok, and? Well, if I type Ctrl + Z to exit the while, the std::cin.clear() works; if I type something that is not Ctrl + Z the std::cin.clear() doesn't work. I want to know why.

Aucun commentaire:

Enregistrer un commentaire