1. Summary
  2. Files
  3. Support
  4. Report Spam
  5. Create account
  6. Log in

Leaves data in input buffer

From cpwiki

Jump to: navigation, search

Certain functions (and objects in C++) can leave data in the input buffer if it tries to read non-string type data (such as int). It does this because it cannot convert the newline character (\n) to a non-string type data (again, such as int). Such functions are:

  • C functions: scanf, fscanf
  • C++ functions (and objects): cin

The following example demonstrates the problem:

  • C version:
int x, y;
printf("Please enter an integer: ");
scanf("%d", &x);
printf("Please enter another integer: ");
scanf("%d", &y);
print("You entered %d and %d.", x, y);
  • C++ version:
int x, y;
std::cout << "Please enter an integer: ";
std::cin >> x;
std::cout << "Please enter another integer: ";
std::cin >> y;
std::cout << "You entered " << x << " and " << y << ".";

Since the first scanf and cin leaves the \n in the input buffer, the second scanf and cin will attempt to read this data and fail, thus not reading another integer as the programmer often desires.

A typical solution to this problem is to add a getchar() for C or cin.ignore() for C++ after each scanf or cin to "eat" the newline in the buffer so that the next scanf and cin will read from the user again instead of trying to read what is left in the input buffer. Thus, a fixed solution to this code might be:

  • C version:
int x, y;
printf("Please enter an integer: ");
scanf("%d", &x);
getchar();
printf("Please enter another integer: ");
scanf("%d", &y);
getchar();
print("You entered %d and %d.", x, y);
  • C++ version:
int x, y;
std::cout << "Please enter an integer: ";
std::cin >> x;
std::cin.ignore();
std::cout << "Please enter another integer: ";
std::cin >> y;
std::cin.ignore();
std::cout << "You entered " << x << " and " << y << ".";
Personal tools