What is the purpose of the getline() function in C++?a)It reads a line...
Answer:
The getline() function in C is used to read a line of text from the console. It is a standard library function defined in the header file . The purpose of this function is to read a line of text, including spaces, from the user and store it in a character array or a string.
Working of getline() function:
1. The getline() function takes three arguments: the address of the character array where the input will be stored, the maximum number of characters to be read, and the file pointer from where the input is to be read.
2. It reads characters from the specified file pointer until it encounters a newline character or the maximum number of characters is read.
3. The newline character ('\n') is also read and stored in the character array.
4. The getline() function then appends a null character ('\0') at the end of the character array to mark the end of the string.
Example usage:
```c
#include
int main() {
char str[100]; // declare a character array to store the input
printf("Enter a line of text: ");
fflush(stdout); // flush the output buffer to display the prompt
fgets(str, sizeof(str), stdin); // use fgets() to read the line of text
printf("You entered: %s", str); // display the input
return 0;
}
```
Explanation:
In the above example, the getline() function is used to read a line of text from the user.
- The character array `str` is declared to store the input.
- The prompt "Enter a line of text: " is displayed using the printf() function.
- The fflush() function is used to flush the output buffer to ensure that the prompt is displayed before reading the input.
- The fgets() function is used to read the line of text from the user. The maximum number of characters to be read is specified as `sizeof(str)`, which ensures that the input does not exceed the size of the character array.
- Finally, the input is displayed using the printf() function.
This is how the getline() function is used to read a line of text from the console in C. It is a convenient way to handle input that includes spaces and newline characters.
What is the purpose of the getline() function in C++?a)It reads a line...
The 'getline()' function is used to read a line of text from the console.