0
#include <iostream>
#include <string>
#include <cstring>
using namespace std;

int main()
{
  int num;
  while(1){
    cin>>num;
    cout<<num<<endl;
  }
  return 0;
}

When I try to run this code, it outputs value of 'num' everytime I input an int. But when I type a string or char for input,it stops asking for input from the next iteration and starts outputting 0 in an infinite loop. Can anyone explain reason behind this?

mrAnderson
  • 69
  • 1
  • 2
  • 7
  • basically, **don't use `operator>>`.** It's clumsy, it's quirky, it's hard to use correctly. Use `std::getline()` instead. – The Paramagnetic Croissant May 13 '15 at 18:15
  • 1
    @TheParamagneticCroissant: It's not really all that difficult to use correctly--in fact, using it correctly is pretty much identical to using `std::getline` correctly. In both cases, you want to do it inside a condition, such as `while (std::cin >> num)` or `while (std::getline(infile, buffer))`. – Jerry Coffin May 13 '15 at 18:19
  • @JerryCoffin that's not the problem here (OP is fortunately not using the oh-so-frequent `while(!eof)` anti-pattern). The problem is that the behavior of `>>` is dependent on the particular overload, the semantics of each overload differing subtly, and who can keep all the overloads in their mind? (not to mention the sloppy automatic "helpful" handling of whitespace that just gets in the way.) – `getline()` has easy-to-remember, uniform semantics, it does only one thing and does it well. In particular, it does not attempt to *parse* the input (which `operator>>` tries, and boy does it fail.) – The Paramagnetic Croissant May 13 '15 at 18:27
  • @TheParamagneticCroissant: It sort of is the problem (or at least one of the problems) though. It goes into an infinite loop because it doesn't detect that its last attempt at parsing input failed, so it just keeps re-trying. A `while (std:cin >> num)` would at least detect that the attempt at reading had failed and quit trying. – Jerry Coffin May 13 '15 at 18:33
  • @JerryCoffin yes, that's correct. – The Paramagnetic Croissant May 13 '15 at 18:57
  • @JerryCoffin I still dont understand why it goes into infinite loop, after cin fails. How cin gets filled with 0 everytime after that? – mrAnderson May 13 '15 at 21:07
  • 2
    The non-numeric characters you entered were put into an input buffer. Each time through the loop, `cin` attempts to interpret those characters as a number, but can't. Since you're not doing anything to remove them from the buffer, it repeatedly attempts to read those same characters as a number, failing every time. You need to get them out of the buffer, then get more input from the user. You can do that by reading an entire line with `std::getline`, then trying to convert its contents to a number, and if it fails, read another line (exactly as @TheParamagneticCroissant advised above). – Jerry Coffin May 13 '15 at 22:15

0 Answers0