Take input till enter is pressed in C++.

 I am assuming that you want to read distinct integer values from a line or a test case until enter is pressed. For example, you need to take space separated integers as input until there is a new line.  

First of all, to take input in C++ what we use is "cin". what "cin" does is that it only takes input until there is a space or new line. It do not reads space, so we can't check if the input is '\n' using only "cin", because it completely ignores this space character. 

So, to make our program read this space we need use a more lower version of function to take input. For this we have ".get()", ".getLine()", ".getChar()". We can use .get() to take any specific number of characters as input or .getLine() to take whole line as input untill enter key is pressed. But here is the thing that is going to help us, And that is .getChar(), which can read only a single character but this single character can also be  a space or a  newline character. 

Now whenever we need to take inputs like the following and we do not know there size :

1 2 3 4 6 7 
2 4 6 7
5 6 7 8 9 0

follow following steps:-

STEP1 : read and save a number using cin
STEP2 : read input using getChar()
STEP3 : check if input in STEP2 is space or newline
STEP4 : if input was space repeat from STEP1/ else if newline or '\n' than break from loop

to make such loop we will use do-while loop

do{
        cin >> a[i];
}while( getChar()!= '\n' )

Comments

Popular posts from this blog

Multiply Strings Leetcode 43 question Correct Solution

In the following table, there are 12 entries in the form nij, where i = 1, 2, 3 and j 1,2,3,4. Each of these entries denotes the largest integer n such that f(n) milliseconds = does not exceed t, where f(n) is the function corresponding to the row of the entry and t is the time corresponding to the column of the entry. For example, for entry n32, we have f(n) = 2^n and t = 1 minute. Hence n32 should be the largest integer n such that 2^n milliseconds is no more than 1 minute.

Longest Palindromic Substring Solution