Good day. There was a problem with C ++. In short - in one line does not occur reading using the input stream cin. Code below. The place where the error occurs is indicated by a comment. Tried to clear the stream before reading user_num_to_sum with cin.clear () - don't help.
#include <iostream> //cin, cout #include <conio.h> //_getch() #include <vector> //vector using std::cout; using std::cin; using std::vector; int main () { vector<int> numbers; // Π²Π΅ΠΊΡΠΎΡ ΠΈΠ· ΡΠ΅Π»ΡΡ
ΡΠΈΡΠ΅Π» int num = 0; // ΡΠΈΡΠ»ΠΎ ΠΊΠΎΡΠΎΡΠΎΠ΅ Π·Π°Π½ΠΎΡΠΈΠΌ Π² ΠΊΠΎΠ½Π΅Ρ Π²Π΅ΠΊΡΠΎΡΠ° int user_num_to_sum = 0; // ΡΠΈΡΠ»ΠΎ ΡΠ»Π΅ΠΌΠ΅Π½ΡΠΎΠ² Π²Π΅ΠΊΡΠΎΡΠ° Π΄Π»Ρ ΡΡΠΌΠΌΠΈΡΠΎΠ²Π°Π½ΠΈΡ(ΠΏΡΠΈΠΌΠ΅Ρ: Π΅ΡΠ»ΠΈ ΡΠΈΡΠ»ΠΎ 3, ΡΠΎ ΡΡΠΌΠΌΠΈΡΡΠ΅ΠΌ ΠΏΠ΅ΡΠ²ΡΠ΅ 3 ΡΠ»Π΅ΠΌΠ΅Π½ΡΠ°) cout << "Write a few numbers: \n"; while(cin >> num) { numbers.push_back(num);// Π·Π°Π½ΠΎΡΠΈΠΌ ΡΠΈΡΠ»Π° Π² Π²Π΅ΠΊΡΠΎΡ } cout << "How much elements of vector do you want to sum?\n"; cin >> user_num_to_sum; // ERROR: ΠΏΡΠΎΠ³ΡΠ°ΠΌΠΌΠ° ΠΏΡΠΎΠΏΡΡΠΊΠ°Π΅Ρ Π΄Π°Π½Π½ΡΡ ΡΡΡΠΎΡΠΊΡ ΠΈ Π²ΡΠΏΠΎΠ»Π½ΡΠ΅Ρ ΡΠ»Π΅Π΄ΡΡΡΡΡ ΠΏΠΎΠ΄ΡΡΠ°Π²Π»ΡΡ Π² user_num_to_sum Π·Π½Π°ΡΠ΅Π½ΠΈΠ΅ 0, ΠΊΠΎΡΠΎΡΠΎΠ΅ Π±ΡΠ»ΠΎ Π·Π°Π΄Π°Π½ΠΎ ΠΏΡΠΈ ΠΈΠ½ΠΈΡΠΈΠ°Π»ΠΈΠ·Π°ΡΠΈΠΈ. cout << "The sum of first " << user_num_to_sum << " numbers -> "; //ΠΊΠΎΠ΄ Π΅ΡΠ΅ Π½Π΅ Π³ΠΎΡΠΎΠ² ΠΏΠΎΠ»Π½ΠΎΡΡΡΡ, ΠΏΡΠΎΠ³ΡΠ°ΠΌΠΌΠ° ΡΠΌΡΡΠ»Π° Π½Π΅ ΠΈΠΌΠ΅Π΅Ρ _getch(); return 0; }
I stop the while loop (cin >> num) by entering the error character '|'. This technique is used in his book Stroustrup. But then for some reason, after stopping the cycle, the reading of the whole number user_num_to_sum does not work.
PS The variant with cin.clear () worked, but only in case of completion of data input into the vector by pressing Ctrl + Z. If you complete it by entering incorrect data (for example, '|' when reading data of type int), then cin.clear () does not work. Question: why?
cin.clear()
helped. - andy.37