0

I don't understand why my 2nd while loop to read input into a vector is not iterating. I've tried using getchar() to flush the input buffer (even tho I think the previous endl does this anyway) between the 1st part (read int vector from input then output) and 2nd part (read string vector from input, then output). Here is the code:

#include <iostream>
#include <string>
#include <cctype>
#include <vector>
using std::cin; using std::cout; using std::endl; using std::string; using std::cerr; using std::vector;

int main() {
    vector<int> numbs; // empty vector
    int inp_num;
    while (cin >> inp_num)
        numbs.push_back(inp_num);

    for (const auto& k : numbs)
        cout << k << " ";
    cout << endl;

    //part 2
    vector<string> text; // empty vector
    string inp_text;
    while (cin >> inp_text)
        text.push_back(inp_text);

    for (const auto& j : text)
        cout << j << " ";
    cout << endl;

    system("pause>0");
    return 0;
}
Spellbinder2050
  • 644
  • 3
  • 13
  • 1
    How are you expecting end of input? By typing a non-number when doing `cin >> inp_num`? – ChrisMM May 15 '21 at 17:59
  • 2
    Does this answer your question? [Why would we call cin.clear() and cin.ignore() after reading input?](https://stackoverflow.com/questions/5131647/why-would-we-call-cin-clear-and-cin-ignore-after-reading-input) – ChrisMM May 15 '21 at 18:00
  • 2
    `while (cin >> inp_num)` executes until a stream error or fail (inlcuding eof). once that happens, every formatted extraction, including the ones succeeding will continue to fail until the stream error state is reset. – WhozCraig May 15 '21 at 18:00

1 Answers1

1

Your problem is that std::cin buffer already contains EOF or other input that will cause second loop to be skipped. Try this:

std::cin.clear();
std::cin.ignore();

right before this part of code

//part 2
vector<string> text; // empty vector
string inp_text;
while (cin >> inp_text)
    text.push_back(inp_text);
  • I thought the point of `getchar();` was to clear the input buffer? Why doesn't `getchar();` work in this case for EOF? – Spellbinder2050 May 15 '21 at 19:59
  • 1
    @Spellbinder2050 Because `getchar()` also sets `EOF` indicator. See return value on this page: http://www.cplusplus.com/reference/cstdio/getchar/ or this page as well https://en.cppreference.com/w/c/io/getchar –  May 15 '21 at 20:17
  • 1
    Or it sets `ERROR` indicator if error occurs. –  May 15 '21 at 20:19