×

Fast Input and Output in C++

In competitive programming, it's critical to read input as quickly as possible in order to save time. "Warning: Big I / O data, be aware of certain languages (but most should be correct if the operating system is sufficiently developed)," you have probably read in many of the problem statements. Faster I / O systems are key to solving such problems.

For faster and more intuitive input, scanf / printf is often recommended over cin / cout. However, by setting the following two lines in your main (), you can still use cin / cout and get the same functionality as scanf / printf:

ios_base :: sync_with_stdio ( false ) ;

When called before the system performs its first input or output action, it turns on or off the synchronization of all normal C ++ streams and your normal C-stream. This sync can be avoided by adding ios base :: sync with stdio ( false ); (which is automatically true) before every I / O action. Stable member std :: ios base function.

cin.tie ( NULL ) ;

tie () is a function that merely ensures that std :: cout is flushed before std :: cin accepts a command. This is handy for interactive console applications that require the console to be updated on a regular basis, but it slows down the program when dealing with big amounts of data. The NULL portion just returns a reference to NULL.

Furthermore, the standard template library (STL) may be included with a single include:

#include < bits/stdc++.h >

As an example, your competitive programming template may look like this:

#include < bits/stdc++.h >
using namespace std ; 
int main ( )
{
    ios_base :: sync_with_stdio ( false ) ;
    cin.tie ( NULL ) ;
    return 0 ;
}

It is preferable to use cout "n"; rather than cout endl;. endl is more time consuming since it requires a flushing stream, which is frequently unneeded. (If you are upgrading, for example, a collaborative progress bar, you will need to delete it, but not if you are writing a million data lines.) Instead of 'house, write' n. Problem INTEST - Enormous Input Teston SPOJ, we may test our inputs and output methods. I recommend that you tackle the problem first before continuing.

Example:

// A normal IO example code
#include < bits/stdc++.h >
using namespace std ;
int main ( )
{
	int n , k , t ;
	int cnt = 0 ;
	cin >> n >> k ;
	for ( int i=0 ; i < n ; i++ )
	{
		cin >> t ;
		if ( t % k == 0 )
			cnt++ ;
	}
	cout << cnt << "\n" ;
	return 0 ;
}

OUTPUT:

0
...
Process executed in 2.11 seconds
Press any key to continue.

Explanation

cin and cout are used in the code below. With a runtime of 2.11 seconds, the solution is acceptable.

Another Example:

// A fast IO program
#include < bits/stdc++.h >
using namespace std ; 
int main ( )
{
	// added the two lines below
	ios_base :: sync_with_stdio ( false ) ;
	cin.tie ( NULL ) ; 
	int n , k , t ;
	int cnt = 0 ;
	cin >> n >> k ;
	for ( int i = 0 ; i < n ; i++ )
	{
		cin >> t ;
		if ( t % k == 0 )
			cnt++ ;
	}
	cout << cnt << "\n" ;
	return 0 ;
}

OUTPUT:

0
...
Process executed in 0.22 seconds
Press any key to continue.

Explanation

By adding two lines, we can improve the performance and significantly cut the runtime. With a runtime of 0.22 seconds.

Another Example:

#include < bits/stdc++.h >
using namespace std;
void fastscan ( int &number )
{
	//variable to indicate sign of input number
	bool negative = false ;
	register int c ; 
	number = 0 ; 
	// extract current character from buffer
	c = getchar ( ) ;
	if ( c == '-' )
	{
		// number is negative
		negative = true ; 
		// extract the next character from the buffer
		c = getchar ( ) ;
	}
	// Keep on extracting characters if they are integers
	// i.e ASCII Value lies from '0'( 48 ) to '9' ( 57 )
	for ( ; ( c > 47 && c < 58 ) ; c=getchar ( ) )
		number = number *10 + c - 48 ; 
	// if scanned input has a negative sign, negate the
	// value of the input number
	if ( negative )
		number *= -1 ;
}
// Function Call
int main ( )
{
	int number ;
	fastscan ( number ) ;
	cout << number << "\n" ;
	return 0 ;
}

OUTPUT:

0
...
Process executed in 0.12 seconds
Press any key to continue.

Explanation:

Now, when it comes to competitive challenges such as the ACM ICPC, Google CodeJam, and TopCoder Open, above is a unique code for reading numbers quickly.


Related Topics

Difference between C and C++

What do you mean by C? C is a machine-independent structure or procedural oriented computer language that is widely utilized in a variety of applications. C is a fundamental programming language...

4 minutes read.

Function Pointer in C++

Definition: A function pointer in C++ is the same as a usual pointer which is used to point some variables. Function pointers are used to point functions or say store the...

4 minutes read.

This keyword in C++

This keyword in C++ is a pointer which points to the object. It is passed as an argument to functions which helps in accessing the object. It is used for a...

3 minutes read.

C++ storage classes

Storage Classes are used to characterize a variable's or function's characteristics. These characteristics include scope, visibility, and life-time, which allow us to track the presence of a variable over the...

5 minutes read.

Naming Convention in C++

The first and most fundamental step a programmer takes to produce clean code is to name a file or a variable. This naming must be acceptable so that it serves...

5 minutes read.

Snake Code in C++

Snake is a popular game that can be played on almost any device and runs on any operating system. In this game, snakes can move in any direction, including left,...

4 minutes read.

C++ | C Plus Plus Data type

Data type in every language is very important. Data type means the different kinds of data that are supported by a particular programming language. A computer language’s data types specify the...

15 minutes read.

Structured Binding in C++

Structured binding is the new feature of C++ 17. It is used to bind the specified name with an element of the initializer. Structure binding is used to declare multiple...

3 minutes read.

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

Diamond Pattern in C++ using For Loop

For Loop: A for loop is a repetitive control structure that allows you to create a loop for executing a specific number of times. The syntax of for loop: In C++, a for...

5 minutes read.

Smart pointers in C++

What are Pointers ? Pointers are often used to keep track of a variable's address. A null value can be assigned to a pointer. Pass by reference can be used to...

6 minutes read.

C++ program to read string using cin.getline()

C++ program to read string using cin.getline() C++ getline() is a standard library feature for reading a string or a line from an input source. A getline() function gets characters from...

3 minutes read.

C++ Enumeration

C++ Enumeration In C++, Enum is a special data type that contains some fixed sets of components that have various applications in the programming. Enum works fine with fixed constant sets...

3 minutes read.

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.

How to make a password program in C++

Before understanding the password program, one must know about a password and why it is required. Password: A password is a word that permits access to somewhere or something. A password...

4 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.

Constructor Overloading in C++

A Constructor is a class member function that is used to initialize the class's objects. Constructors have no return type and are called automatically when an object is formed. Constructor Characteristics Constructors...

3 minutes read.

C++ Program to Implement Shell Sort

    C++ Program to Implement Shell Sort shell sort is basically an Insertion Sort variant. In the insertion sort, we only transfer elements ahead of one location. Many movements are involved...

2 minutes read.

Reverse a String using Stack C/C++

Reverse the given string using stack. To turn "tutorialandexample" into "elpmaxednalairotut," for instance. Here is a straightforward stack-based technique for reversing strings. Algorithm: 1) Make a stack that is empty. 2) Push each character...

3 minutes read.

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.