1

Is there a way I can have a user input a bunch of integers consecutively, but when she/he is done she/he would press -111 (must be this number) when finished without having to initialize another data type?

Like this:

while(what the user puts in is not -111)

Loie Benedicte
  • 149
  • 1
  • 10
  • I mean that is memory-efficient and quick. – Loie Benedicte Aug 02 '13 at 00:07
  • Do I just have to have `int dummy_input` no matter what? – Loie Benedicte Aug 02 '13 at 00:08
  • what is the language? and what platform? – Jafar Kofahi Aug 02 '13 at 00:12
  • Please [edit] your question to provide at least a tag for the language you're asking about, as well as some code that indicates you've at least made some effort to complete your assignment yourself before asking here. We like to try and be helpful, but we're not going to do your homework for you without some effort on your part. :-) – Ken White Aug 02 '13 at 00:22
  • 3
    Just as an aside, has anybody ever tried mixing their coffee with fresh Thai chile, and Yerba Mate? It's great! Not too spicy, smooth, it's pretty good, and I recommend it. Hopefully you'll see this before it gets deleted. – Loie Benedicte Aug 02 '13 at 00:42
  • The integers will be pumped into a vector of integers as the user types them in, and I don't want -111 in the vector. Perhaps it should instead be a do-while loop. – Loie Benedicte Aug 02 '13 at 00:44
  • Look at this: http://stackoverflow.com/a/421871/2293156 – Amadeus Aug 02 '13 at 00:53
  • @TomásBadan I'm not sure if that's what the OP is asking. I think he/she is just looking at the much simpler problem of reading until some specific number is given. It would be nice if the OP could clarify this. – Zong Aug 02 '13 at 00:55
  • @ZongZhengLi Maybe you are right. I had understood (s)he wants to read the input buffer in an unbuffered mode. Maybe it is a simpler question. – Amadeus Aug 02 '13 at 01:06

2 Answers2

2

How about this

  int i;   
  do {
    std::cin >> i;
  } while (i != -111);
skuzniar
  • 121
  • 4
2

This is extremely simple. But the other answer doesn't even handle end of input, so this is better

int i;
while (cin >> i && i != -111) {
    ...
}
Zong
  • 6,160
  • 5
  • 32
  • 46
  • What exactly is better? The other answer handles the end of input correctly. In fact, it's more robust than your's - you rely on operator precedence and order of evaluation to get the result (either intentional or not) - that's can be broken easily and you end up with unexpected behavior due to usage of uninitialized variable – SomeWittyUsername Aug 02 '13 at 06:00
  • @icepack: The other answer doesn't handle end-of-file or malformed input. The order of evaluation in this code is well defined, `i` won't be tested unless `cin` was able to read an integer value. – Blastfurnace Aug 02 '13 at 06:10