1
votes

I know that this is a common question but i could not find any solution to this question without using vectors and ctrl + d/c. I have encounter a infinite while loop while using cin to get a unknown amount of integer. the while loop does not stop executing even after a enter in pressed. Thanks a lot!

while(cin >> num)
{
    num--;
    sizeB = 0;
    setB[sizeB] = num;
    sizeB++;
}
cin.ignore();
cin.clear();
2
Whitespace is ignored in formatted input operations. A newline is whitespace. Maybe you want to use getline instead?Zeta
If num is an integer than typing letters and pressing Enter will cause the loop to exitM.M
@MarcoA the condition is cin. (operator>> returns reference to cin). It's equivalent to doing !cin.fail(), i.e. check that neither end-of-file occurred, nor that something was typed which failed to be converted to the type of num.M.M
@Zeta I am sorry i could not use getline as if i use get line it will be read all the values as one sentence.Aurora_rainbow
@MattMcNabb I'm not used to this usecase, that's definitely true (cplusplus.com/reference/ios/ios/operator_bool). To be precise 'does not return the same as member good, but the opposite of member fail'Marco A.

2 Answers

2
votes

It is possible to use getline function to get data line-by-line, then read values via a stringstream:

#include <iostream>
#include <stdio.h>
#include <sstream>

using namespace std;

int main() {
  string line;
  while(getline(cin, line)) {
    stringstream str_stream(line);
    int num;
    while(str_stream >> num) {
      cout << "..." << num << "..." << endl;
    }
    cout << "----" << endl;
  }
}
0
votes

while takes a bool argument. In your code, cin >> num returns an istream&, that is converted calling istream::operator bool() (and I'd guess evaluates to true if the stream is not closed)

read a string and convert it to int, break when the string is empty:

while (1) {
   std::string theString;
   std::getline(std::cin, theString);
   if (theString.empty())
      break;
   int num= atoi(theString.c_str());
   ...
}