C+++. The program passes the code line(s)



  • Good night. There's a problem with C++. In short, one line does not read by cin input flow. Code down. The place where the error occurs is marked by a comment. I tried to clean the flow before reading. user_num_to_sum by 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 &lt;&lt; "Write a few numbers: \n";
    while(cin &gt;&gt; num) {
        numbers.push_back(num);// заносим числа в вектор
        }
    cout &lt;&lt; "How much elements of vector do you want to sum?\n";
    cin &gt;&gt; user_num_to_sum; // ERROR: программа пропускает данную строчку и выполняет следующую подставляя в user_num_to_sum значение 0, которое было задано при инициализации.
    cout &lt;&lt; "The sum of first " &lt;&lt; user_num_to_sum &lt;&lt; " numbers -&gt; ";
    

    //код еще не готов полностью, программа смысла не имеет

    _getch();
    
    return 0;
    

    }

    I'm stopping the cycle while I'm putting the erroneous symbol ">." This reception is used in his book Straustrup. Only then, after the cycle stops, it doesn't work to read the whole number of user_num_to_sum.

    P.S. Use case worked cin.clear()but only if the data entry into the vector is completed by compression of Ctrl+Z.
    If we complete it by entering the wrong data (for example, '|' when we read the type int, then cin.clear() It doesn't work. Question: Why?



  • while(cin >> num) { // Пока мы можем прочитать int, читаем его
      ... // и что-то делаем
    }
    
    // Вышли из цикла, т. к. int прочитать нельзя
    ... // Тут мы ничего не читали
    cin >> user_num_to_sum; // Опа! Чиатем ещё int
    

    But the state of the flow hasn't changed - int could not have been read, and not now.

    If the introduction of the sequence of the numbers ends with some inaccurate entry, it should be read as a line and only read the following number. If the introduction was completed with a ctrl+z, it's like eof.

    Also, to throw a marker out, a mistake has to be made before reading. cin.clear()




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2