In C programming, the standard way to scan a line of text with spaces separating words is to use the fgets()
function.
The fgets()
function reads a line of input from a stream (such as stdin
for keyboard input) and stores it in a character array. It takes three arguments: the character array to store the input, the maximum number of characters to read, and the input stream to read from.
Here's an example of using fgets()
to scan a line of input with spaces:
int main() {
char input[100];
printf("Enter a line of text: ");
fgets(input, 100, stdin);
printf("You entered: %s", input);
return 0;
}
In this example, we declare a character array input
with a size of 100 to store the line of text. We then prompt the user to enter a line of text using printf()
. The fgets()
function is then used to read the line of text and store it in the input
array. The third argument, stdin
, specifies that the input should be read from the standard input stream (i.e. the keyboard).
The %s
format specifier is used in the printf()
statement to print the contents of the input
array, which contains the scanned line of text.
Note that fgets()
reads and stores the newline character \n
at the end of the input line. If you want to remove this newline character, you can use the strtok()
function to tokenize the string and replace the \n
character with a null terminator.
Here's an example of using fgets()
and strtok()
to remove the newline character:
int main() {
char input[100];
printf("Enter a line of text: ");
fgets(input, 100, stdin);
// Remove the newline character
strtok(input, "\n");
printf("You entered: %s", input);
return 0;
}
In this example, the strtok()
function is used to tokenize the input
string and replace the newline character \n
with a null terminator. The "\n"
argument specifies the delimiter to use for tokenization.
By using fgets()
and optionally strtok()
, you can easily scan a line of input with spaces separating words in C programming.
Comments
Post a Comment