12

What is the difference between cin.ignore and cin.sync ?

Kevin Panko
  • 8,356
  • 19
  • 50
  • 61
5fox
  • 163
  • 2
  • 2
  • 11

1 Answers1

17

cin.ignore discards characters, up to the number specified, or until the delimiter is reached (if included). If you call it with no arguments, it discards one character from the input buffer.

For example, cin.ignore (80, '\n') would ignore either 80 characters, or as many as it finds until it hits a newline.

cin.sync discards all unread characters from the input buffer. However, it is not guaranteed to do so in each implementation. Therefore, ignore is a better choice if you want consistency.

cin.sync() would just clear out what's left. The only use I can think of for sync() that can't be done with ignore is a replacement for system ("PAUSE");:

cin.sync(); //discard unread characters (0 if none)
cin.get(); //wait for input

With cin.ignore() and cin.get(), this could be a bit of a mixture:

cin.ignore (std::numeric_limits<std::streamsize>::max(),'\n'); //wait for newline
//cin.get()

If there was a newline left over, just putting ignore will seem to skip it. However, putting both will wait for two inputs if there is no newline. Discarding anything that's not read solves that problem, but again, isn't consistent.

chris
  • 60,560
  • 13
  • 143
  • 205
  • can you show me specific implementations that cin.sync not safe! – 5fox May 14 '12 at 14:57
  • 1
    @5fox: I can show you implementations where it doesn't do a thing: http://ideone.com/AR8lB – Benjamin Lindley May 14 '12 at 15:01
  • ignore() should be called before cin or after cin? To be specific, first time when I go for cin, do I need to flush unwanted data in the buffer if any? Or will program flush everything when main is entered? But what I noticed is that if we call ignore(), it waits for some non white space character first time. – Rajesh Mar 11 '18 at 02:49
  • @Rajesh, After. The input buffer shouldn't have random stuff in it when the program starts. The common use case for this is clearing bad user-entered input or getting rid of a newline left over by an input operation. – chris Mar 11 '18 at 04:02
  • @chris Thaks for the info. Why do my below code fails to accept string? In case empty string is entered, I want while loop to ask user for new string. Code does not work for empty string or for valid string. ignore() lines is troubling me it looks and if i remove ignore(), things work. But I am worried if it may give trouble later since I am not flushing the buffer. void getString(string &str) { do { cout<<"Enter the String: "; getline(std::cin,str); cin.ignore (std::numeric_limits::max(),'\n'); } while (str.empty()); } – Rajesh Mar 12 '18 at 02:35
  • @Rajesh, That's really suited for a new question rather than the comments of a six-year-old question. – chris Mar 12 '18 at 04:41