The Wayback Machine - https://web.archive.org/web/20241031185251/https://www.geeksforgeeks.org/clearing-the-input-buffer-in-cc/
Open In App

Clearing The Input Buffer In C/C++

Last Updated : 11 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

What is a buffer? 

A temporary storage area is called a buffer. All standard input and output devices contain an input and output buffer. In standard C/C++, streams are buffered. For example, in the case of standard input, when we press the key on the keyboard, it isn’t sent to your program, instead of that, it is sent to the buffer by the operating system, till the time is allotted to that program.

How does it affect Programming? 

On various occasions, you may need to clear the unwanted buffer so as to get the next input in the desired container and not in the buffer of the previous variable. For example, in the case of C after encountering “scanf()”, if we need to input a character array or character, and in the case of C++, after encountering the “cin” statement, we require to input a character array or a string, we require to clear the input buffer or else the desired input is occupied by a buffer of the previous variable, not by the desired container. On pressing “Enter” (carriage return) on the output screen after the first input, as the buffer of the previous variable was the space for a new container(as we didn’t clear it), the program skips the following input of the container. The C++ Course includes techniques for clearing the input buffer, ensuring your programs run smoothly without unexpected behavior.

In the case of C Programming 

C
// C Code to explain why not
// clearing the input buffer
// causes undesired outputs
#include <stdio.h>
int main()
{
    char str[80], ch;

    // Scan input from user -
    // GeeksforGeeks for example
    scanf("%s", str);

    // Scan character from user-
    // 'a' for example
    ch = getchar();

    // Printing character array,
    // prints “GeeksforGeeks”)
    printf("%s\n", str);

    // This does not print
    // character 'a'
    printf("%c", ch);

    return 0;
}

Input: 

GeeksforGeeks
a

Output: 

GeeksforGeeks

Time Complexity: O(1) 

In the case of C++ 

C++
// C++ Code to explain why
// not clearing the input 
// buffer causes undesired
// outputs
#include<iostream>
#include<vector>
using namespace std;

int main()
{
    int a;
    char ch[80];
    
    // Enter input from user 
    // - 4 for example
    cin >> a;
    
    // Get input from user -
    // "GeeksforGeeks" for example
    cin.getline(ch,80);
    
    // Prints 4
    cout << a << endl;
    
    // Printing string : This does 
    // not print string
    cout << ch << endl;
    
    return 0;
}

Input: 

4
GeeksforGeeks

Output: 

4

Time Complexity: O(1)

In both of the above codes, the output is not printed as desired. The reason for this is an occupied Buffer. The “\n” character goes remains there in the buffer and is read as the next input.

How can it be resolved?

In the case of C:  

1. Using “ while ((getchar()) != ‘\n’); ”: Typing “while ((getchar()) != ‘\n’);” reads the buffer characters till the end and discards them(including newline) and using it after the “scanf()” statement clears the input buffer and allows the input in the desired container.

C
// C Code to explain why adding 
// "while ( (getchar()) != '\n');"
// after "scanf()" statement 
// flushes the input buffer
#include<stdio.h>

int main()
{
    char str[80], ch;
    
    // scan input from user - 
    // GeeksforGeeks for example
    scanf("%s", str);
    
    // flushes the standard input
    // (clears the input buffer)
    while ((getchar()) != '\n');
    
    // scan character from user - 
    // 'a' for example
    ch = getchar();
    
    // Printing character array, 
    // prints “GeeksforGeeks”)
    printf("%s\n", str);
    
    // Printing character a: It 
    // will print 'a' this time
    printf("%c", ch);

    return 0;
}

Input: 

GeeksforGeeks
a

Output: 

GeeksforGeeks
a

Time Complexity: O(n), where n is the size of the string. 

2. Using “ fflush(stdin) ”: Typing “fflush(stdin)” after “scanf()” statement, also clears the input buffer but generally it’s use is avoided and is termed to be “undefined” for input stream as per the C++11 standards.

In the case of C++:  

1. Using “ cin.ignore(numeric_limits::max(),’\n’); ” :- Typing “cin.ignore(numeric_limits::max(),’\n’);” after the “cin” statement discards everything in the input stream including the newline. 

C++
// C++ Code to explain how
// "cin.ignore(numeric_limits
// <streamsize>::max(),'\n');"
// discards the input buffer
#include <iostream>

// for <streamsize>
#include <ios>

// for numeric_limits
#include <limits>
using namespace std;

int main()
{
    int a;
    char str[80];

    // Enter input from user
    // - 4 for example
    cin >> a;

    // discards the input buffer
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    // Get input from user -
    // GeeksforGeeks for example
    cin.getline(str, 80);

    // Prints 4
    cout << a << endl;

    // Printing string : This
    // will print string now
    cout << str << endl;

    return 0;
}

Input: 

4
GeeksforGeeks

Output: 

4
GeeksforGeeks

Time Complexity: O(1) 

2. Using “ cin.sync() ”: Typing “cin.sync()” after the “cin” statement discards all that is left in the buffer. Though “cin.sync()” does not work in all implementations (According to C++11 and above standards). 

C++
// C++ Code to explain how " cin.sync();"
// discards the input buffer
#include <ios>
#include <iostream>
#include <limits>

using namespace std;

int main()
{
    int a;
    char str[80];

    // Enter input from user
    // - 4 for example
    cin >> a;

    // Discards the input buffer
    cin.sync();

    // Get input from user -
    // GeeksforGeeks for example
    cin.getline(str, 80);

    // Prints 4
    cout << a << endl;

    // Printing string - this
    // will print string now
    cout << str << endl;

    return 0;
}

Input: 

4
GeeksforGeeks

Output: 

4

Time Complexity: O(1) 

3. Using “ cin >> ws ”: Typing “cin>>ws” after “cin” statement tells the compiler to ignore buffer and also to discard all the whitespaces before the actual content of string or character array. 

C++
// C++ Code to explain how "cin >> ws" 
// discards the input buffer along with 
// initial white spaces of string

#include<iostream>
#include<vector> 
using namespace std;

int main()
{
    int a;
    string s;
    
    // Enter input from user -
    // 4 for example
    cin >> a;
    
    // Discards the input buffer and
    // initial white spaces of string
    cin >> ws;
    
    // Get input from user - 
    // GeeksforGeeks for example
    getline(cin, s);
    
    // Prints 4 and GeeksforGeeks : 
    // will execute print a and s
    cout << a << endl;
    cout << s << endl;

    return 0;
}

Input: 

4
GeeksforGeeks

Output: 

4
GeeksforGeeks

Time Complexity: O(1) 

4.Using “ fflush(stdin) ”: Typing “fflush(stdin)” after taking the input stream by “cin” statement also clears the input buffer by prompting the ‘\n’ to the nextline literal but generally it is avoided as it is only defined for the C++ versions below 11 standards.

C++
// C++ Code to explain working of "flush(stdin);"
// discards the input buffer
#include <cstdio> //fflush(stdin) is available in cstdio header files
#include <ios>
#include <iostream>
using namespace std;

int main()
{
    int value;
    string letters;

    // Enter an integer input from user
    // 98 for example
    cin >> value;

    // Discards the input buffer
    fflush(stdin);

    // Get input from user -
    // GeeksforGeeks for example
    getline(cin, letters);

    // Prints 98
    cout << value << endl;

    // Printing user entered string - this
    // will print string now
    cout << letters << endl;

    return 0;
}

// This code is contributed by im_impossible_ksv

Input:

369
geeksforgeeks

Output:

369
geeksforgeeks

Time Complexity: O(1)


 



Similar Reads

Clearing Bits in C
In C programming, clearing a bit is the process of setting a specific bit of the binary number to 0. This operation is crucial in various applications, including memory management, data processing, and hardware control. In this article, we will learn how to clear a bit at a given position in a binary number. We will also explore how to clear multip
3 min read
Clearing Bits in C++
In C++ programming, clearing a bit involves setting the value of a specific bit in a binary number to 0. This operation is useful in various applications such as bit masking, controlling hardware, and optimizing algorithms. In this article, we will learn how to clear a bit at a given position in a binary number. Additionally, we will examine how to
4 min read
Stack-buffer based STL allocator
It is absolutely possible to develop a stack allocator that completely complies with C++11 and C++14. However, you must take into account some of the implications of stack allocation's implementation, semantics, and interactions with common containers. Here is a fully compliant stack allocator for C++11 and C++14:- Stack buffer: When information wr
4 min read
Buffer in C Programming
In C, the buffer is referred to as a sequential section of memory that is used to temporarily store some data that is being transferred from one place to another. For Example, in C language, the data entered using the keyboard is first stored in the input buffer, and then it is stored in the memory. In this article, we will discuss what is a buffer
5 min read
Buffer Overflow Attack with Example
A buffer is a temporary area for data storage. When more data (than was originally allocated to be stored) gets placed by a program or system process, the extra data overflows. It causes some of that data to leak out into other buffers, which can corrupt or overwrite whatever data they were holding.In a buffer-overflow attack, the extra data someti
3 min read
What does buffer flush means in C++ ?
A buffer flush is the transfer of computer data from a temporary storage area to the computer's permanent memory. For instance, if we make any changes in a file, the changes we see on one computer screen are stored temporarily in a buffer. Usually, a temporary file comes into existence when we open any word document and is automatically destroyed w
3 min read
C | Input and Output | Question 13
Predict the output of following program? #include "stdio.h" int main() { char arr[100]; printf("%d", scanf("%s", arr)); /* Suppose that input value given for above scanf is "GeeksQuiz" */ return 1; } (A) 9 (B) 1 (C) 10 (D) 100 Answer: (B) Explanation: In C, scanf returns the no. of inputs it has successfully
1 min read
C | Input and Output | Question 2
Predict output of the following program C/C++ Code #include int main() { printf("\new_c_question\b\r"); printf("geeksforgeeks"); getchar(); return 0; } (A) ew_c_questiongeeksforgeeks (B) new_c_quesgeeksforgeeks (C) geeksforgeeks (D) Depends on terminal configuration Answer: (D) Explanation: See https://stackoverflow.com/questions/17236242/usage-of-
1 min read
C | Input and Output | Question 3
#include <stdio.h> int main() { printf(" \"GEEKS %% FOR %% GEEKS\""); getchar(); return 0; } (A) “GEEKS % FOR % GEEKS” (B) GEEKS % FOR % GEEKS (C) \"GEEKS %% FOR %% GEEKS\" (D) GEEKS %% FOR %% GEEKS Answer: (A) Explanation: Backslash (\\\\) works as escape character for double quote (“). For explanation of %%, see https://
1 min read
C | Input and Output | Question 4
C/C++ Code #include // Assume base address of \"GeeksQuiz\" to be 1000 int main() { printf(5 + \"GeeksQuiz\"); return 0; } (A)GeeksQuiz (B)Quiz (C)1005 (D)Compile-time error Answer: (B)Explanation: printf is a library function defined under stdio.h header file. The compiler adds 5 to the base address of the string through the expression 5 + \"Geeks
1 min read
C | Input and Output | Question 5
Predict the output of the below program: C/C++ Code #include int main() { printf(\"%c \", 5[\"GeeksQuiz\"]); return 0; } (A) Compile-time error (B) Runtime error (C) Q (D) s Answer: (C) Explanation: The crux of the program lies in the expression: 5[\"GeeksQuiz\"] This expression is broken down by the compiler as: *(5 + \"GeeksQuiz\"). Adding 5 to t
1 min read
C | Input and Output | Question 6
Predict the output of below program: #include <stdio.h> int main() { printf("%c ", "GeeksQuiz"[5]); return 0; } (A) Compile-time error (B) Runtime error (C) Q (D) s Answer: (C) Explanation: The crux of the program lies in the expression: "GeeksQuiz"[5]. This expression is broken down by the compiler as: *(“GeeksQuiz” + 5).
1 min read
C | Input and Output | Question 9
What does the following C statement mean? C/C++ Code scanf(\"%4s\", str); (A)Read exactly 4 characters from console. (B)Read maximum 4 characters from console. (C)Read a string str in multiples of 4 (D)Nothing Answer: (B)Explanation: Try following program, enter GeeksQuiz, the output would be \"Geek\" #include <stdio.h> int main() { char str[
1 min read
C | Input and Output | Question 13
#include<stdio.h> int main() { char *s = "Geeks Quiz"; int n = 7; printf("%.*s", n, s); return 0; } (A) Geeks Quiz (B) Nothing is printed (C) Geeks Q (D) Geeks Qu Answer: (C) Explanation: .* means The precision is not specified in the format string, but as an additional integer value argument preceding the argument that ha
1 min read
C | Input and Output | Question 11
Predict the output of following program? #include <stdio.h> int main(void) { int x = printf("GeeksQuiz"); printf("%d", x); return 0; } (A) GeeksQuiz9 (B) GeeksQuiz10 (C) GeeksQuizGeeksQuiz (D) GeeksQuiz1 Answer: (A) Explanation: The printf function returns the number of characters successfully printed on the screen. The st
1 min read
C | Input and Output | Question 12
Output of following program? #include<stdio.h> int main() { printf("%d", printf("%d", 1234)); return 0; } (A) 12344 (B) 12341 (C) 11234 (D) 41234 Answer: (A) Explanation: printf() returns the number of characters successfully printed on the screen.Quiz of this Question
1 min read
C | Input and Output | Question 13
What is the return type of getchar()? (A) int (B) char (C) unsigned char (D) float Answer: (A) Explanation: The return type of getchar() is int to accommodate EOF which indicates failure:Quiz of this Question
1 min read
Check input character is alphabet, digit or special character
All characters whether alphabet, digit or special character have ASCII value. Input character from the user will determine if it's Alphabet, Number or Special character.ASCII value ranges- For capital alphabets 65 - 90For small alphabets 97 - 122For digits 48 - 57 Examples : Input : 8 Output : Digit Input : E Output : Alphabet C/C++ Code // CPP pro
3 min read
Input an integer array without spaces in C
How to input a large number (a number that cannot be stored even in long long int) without spaces? We need this large number in an integer array such that every array element stores a single digit. Input : 10000000000000000000000000000000000000000000000 We need to read it in an arr[] = {1, 0, 0...., 0} In C scanf(), we can specify count of digits t
2 min read
Find the maximum sum (a+b) for a given input integer N satisfying the given condition
Given an integer N, the task is to find the largest sum (a + b) {1 ? a ? N, 1 ? b ? N} such that a * b/(a + b) is an integer (i.e a + b divides a * b) and a != b. Examples: Input: N = 10 Output: 9 Explanation: The numbers a = 3 and b = 6 leads to sum = 9 also 6 * 3 = 18 which is divisible by 6 + 3 = 9 Input: N = 20 Output: 27 Naive Approach: The id
11 min read
How to input or read a Character, Word and a Sentence from user in C?
C is a procedural programming language. It was initially developed by Dennis Ritchie as a system programming language to write an operating system. The main features of the C language include low-level access to memory, a simple set of keywords, and a clean style, these features make C language suitable for system programmings like operating system
4 min read
Formatted and Unformatted Input/Output functions in C with Examples
This article focuses on discussing the following topics in detail- Formatted I/O Functions.Unformatted I/O Functions.Formatted I/O Functions vs Unformatted I/O Functions.Formatted I/O Functions Formatted I/O functions are used to take various inputs from the user and display multiple outputs to the user. These types of I/O functions can help to dis
9 min read
C++ Wait for User Input
Waiting for User input is common functionality in any program requiring some form of user intervention. Whether it is halting the execution to see the output produced, or is it for taking in user input, halting the execution for input is one of the most common tasks that are performed by a program. In this article, you will learn different methods
4 min read
Input/Output Operators Overloading in C++
Operator Overloading is a part of Polymorphism, which enables the feature because of which we can directly use operators with user-defined classes and objects. To read more about this, refer to the article operator overloading in C++. Input/Output Operators(>>/<<) Overloading in C++ We can't directly use the Input/Output Operators (>
2 min read
How to Take Input in Array in C++?
Arrays in C++ are derived data types that can contain multiple elements of the same data type. They are generally used when we want to store multiple elements of a particular data type under the same name. We can access different array elements using their index as they are stored sequentially in the memory. We can also assign some value to these e
3 min read
How to use getline() in C++ when there are blank lines in input?
In C++, if we need to read a few sentences from a stream, the generally preferred way is to use the getline() function as it can read string streams till it encounters a newline or sees a delimiter provided by the user. Also, it uses <string.h> header file to be fully functional. Here is a sample program in c++ that reads four sentences and d
2 min read
getchar_unlocked() – Faster Input in C/C++ For Competitive Programming
getchar_unlocked() is similar to getchar() with the exception that it is not thread-safe. This function can be securely used in a multi-threaded program if and only if they are invoked when the invoking thread possesses the (FILE*) object, as is the situation after calling flockfile() or ftrylockfile(). Syntax: int getchar_unlocked(void); Example:
2 min read
Input Iterators in C++
After going through the template definition of various STL algorithms like std::find, std::equal, std::count, you must have found their template definition consisting of objects of type Input Iterator. So what are they and why are they used?Input iterators are one of the five main types of iterators present in the C++ Standard Library, others being
6 min read
Taking String input with space in C (4 Different Methods)
We can take string input in C using scanf("%s", str). But, it accepts string only until it finds the first space. There are 4 methods by which the C program accepts a string with space in the form of user input.Let us have a character array (string) named str[]. So, we have declared a variable as char str[20]. Method 1 : Using getsSyntax : char *ge
2 min read
Input-output system calls in C | Create, Open, Close, Read, Write
System calls are the calls that a program makes to the system kernel to provide the services to which the program does not have direct access. For example, providing access to input and output devices such as monitors and keyboards. We can use various functions provided in the C Programming language for input/output system calls such as create, ope
10 min read
Practice Tags :
three90RightbarBannerImg