In this write-up, we will use the built-in functions of C programming that can be used to read the input by the stdin.
How to read a line from stdin in C programming
There are different built-in functions used in c programming for reading the inputs from the stdin. The functions used for reading the lines are:
- getline()
- getchar()
- putchar()
- scanf()
We will explain all these functions in detail.
getline(): This function is used to read the lines from the stdin. To understand this function, let us consider the example, we will create a text file with the name myfile2.c and write the following script:
Compile the script of file2.c using the gcc compiler:
Run the code using the command:
In the above output, we can see that a line is taken from the stdin and then displayed with the count of its characters. The getline() function reads a full sentence from the stdin and allocates some memory on the heap and saves it there. In the getline() we pass the address of the memory where the line should be stored, the address of the length of the line, and the stdin. Then simply display the line and its length using the printf() function. Moreover, in the end, we used free() so that the space occupied in memory can be cleared to re-use it next time.
getchar(): The getchar() function is used to read the first character of the stdin and the putchar() is used to display the single character on the screen. The drawback of the getchar() and putchar() is that they can read and display only one character at a time but we can use a loop to display all the characters of stdin. To understand this, write the following code:
Compile the code using the gcc compiler:
Execute the myfile4:
In the above code, we input a line “Hello! It’s Linuxhint” and the getchar() reads the first character of the line, and putchar() is used to display the line. First, we have asked the user about the length of the string and then we displayed it with the help of a loop.
scanf(): The other widely used method to read the line from the stdin is using the “scanf()” function. The scanf takes the input from the stdin, then scans it and saves it in some variable or array. For example:
Using the gcc compiler, compile the program of myfile5.c to debug the errors:
Execute the myfile5:
In the above script, we simply declared the array “a” with the character data type, with the help of scanf() we took the input from the stdin. We used the “%s” constant which is used to read and print the strings too. Then displayed the string stored in array a[] that is “Hello”.
Conclusion
The stdin is used for taking the input from the keyboard and it can read in different ways. There are different functions used for reading the stdin. In this write-up, we have used different functions used to read a line. The built-in function in c programming is getline() which is used for reading the lines from the stdin. But we can also use other functions like getchar() and scanf() for reading the lines.