Spellbinder2050
Spellbinder2050

Reputation: 652

Program skipping second while loop (reading into int and string vectors respectively using cin)

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;
}

Upvotes: 0

Views: 107

Answers (1)

user5550963
user5550963

Reputation:

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);

Upvotes: 1

Related Questions