Reputation: 35
int k;
vector<int>v;
while ((scanf("%d", &k)) != EOF) {
if (v.size() > 20) break;
else {
if (k > 0 && k <= 120) v.push_back(k);
}
}
**The above snippet is taken from codechef blogs **
Upvotes: 1
Views: 52
Reputation: 149185
<rant>Never tag a question both C and C++ on SO again. It is reserved for questions about interoperations or very specific language-lawyer points, and should not be used for code that could be more or less used on both languages. In that latter case choose one in your first question and if you later need it ask a new question for the other language</rant>
Your problem is that for the scanf
family questions spaces and newlines are just ignored when you use a %d
conversion character. And scanf
returns the number of elements that could be decoded and only stops on an end of file, read error or conversion error.
If you want to be able to detect an empty input, you will have to use fgets
+ sscanf
from the C standard library, or getline
+ stringstream
from the C++ one.
Upvotes: 3