Reputation: 31
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();
Upvotes: 1
Views: 1843
Reputation: 355
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;
}
}
Upvotes: 2
Reputation: 1582
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());
...
}
Upvotes: 0