cin.sync() the reference example code doesn't work

This is the cplusplus reference code, I tried it, and it didn't work as it should be, it didn't stop for the second input and printed the output after the first input directly.
any help, please

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  // syncing input stream
#include <iostream>     // std::cin, std::cout

int main () {
  char first, second;

  std::cout << "Please, enter a word: ";
  first = std::cin.get();
  std::cin.sync();

  std::cout << "Please, enter another word: ";
  second = std::cin.get();

  std::cout << "The first word began by " << first << '\n';
  std::cout << "The second word began by " << second << '\n';

  return 0;
}


output:

Please, enter a word: test
Please, enter another word: The first word began by t
The second word began by e
Last edited on
it is implementation-defined whether this function does anything with library-supplied streams. The intent is typically for the next read operation to pick up any changes that may have been made to the associated input sequence after the stream buffer last filled its get area. To achieve that, sync() may empty the get area, or it may refill it, or it may do nothing.
https://en.cppreference.com/w/cpp/io/basic_istream/sync#Notes
@JLBorges
both examples didn't work on online compiler, clion, or codeBlocks, How can I know which platform or compiler it works with.
Last edited on
> How can I know which platform or compiler it works with.

Check it out on the implementations that you have.

When I tried it, it appears to work as you expect it to work with
clang++ 9.0.0 and g++ 9.2.0 on MSYS2 MinGW64
both examples didn't work on online compiler, clion, or codeBlocks

Those are IDE's, not compilers. As far as I know they could all be the exact same compiler and OS since you haven't mentioned those.

How can I know which platform or compiler it works with.

Compilers need to document implementation-defined behaviour, but relying on it would make the program non-portable. The portable way to clear the buffer is something like:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <limits>

int main () {
  char first, second;

  std::cout << "Please, enter a word: ";
  first = std::cin.get();
  std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

  std::cout << "Please, enter another word: ";
  second = std::cin.get();
  std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

  std::cout << "The first word began by " << first << '\n';
  std::cout << "The second word began by " << second << '\n';

  return 0;
}

Topic archived. No new replies allowed.