I have two WHILE loops and the second one skips

2

I am trying to make a program for which I need to store different values in two vectors. To read the values I use two equal WHILE loops, but the one from the second vector is skipped. What happens?

The final goal is to see if one vector is a prefix of the other, example: {1,3,4,5,7} and {1,3,4} would come true.

vector<int> vecA, vecB, small, large;
int elem;
int elem2, in = 0;
string prefix = "true";
std::cout << "Enter numbers for the first vector: " << std::endl;
while (std::cin >> elem)        // read until end-of-file or cin read invalid data input
    vecA.push_back(elem);
std::cout << "Enter numbers for the second vector: " << std::endl;
while (std::cin >> elem2)       // read until end-of-file or cin read invalid data input
    vecB.push_back(elem2);
if (vecA.size() < vecB.size()) {
    small = vecA;
    large = vecB;
}
else {
    large = vecA;
    small = vecB;
}
for (auto &r : small) {
    if (r != large[in]) { prefix = "false"; break; }
    in++;
}

std::cout << "Prefix is " << prefix << std::endl;
    
asked by MAP 12.09.2018 в 10:12
source

1 answer

2

The first loop is executed until the reading fails, that is, until you enter a character that can not be converted to a number. Then you try to repeat a second loop that does exactly the same thing ... but it does not run once.

When a reading fails (to exit the first loop), the erroneous data is not removed from the stream , and it makes sense ... How many characters should be discarded exactly? one? Two maybe? Until the line break? ?

It is your responsibility to clean the buffer and for this you have to do two things:

  • Clean the error flags, cin will be blocked until this is done:

    std::cin.clear();
    
  • Remove the characters that do not work for you. For this, the usual thing is to discard everything until the first line break:

    std::cin.ignore(std::numeric_limits<int>::max(),'\n');
    

    numeric_limits is a template, in this case max() returns the highest number you can store in a int . What ignore does in this case is to eliminate as many characters as the first parameter marks, unless a line break is encountered before, in which case it discards it and stops the cleaning loop.

  • answered by 12.09.2018 / 10:26
    source