C Program to accept a sentence using scanf function.
Objective
Write a C program to accept a full sentence containing spaces using the scanf function.
Algorithm / Approach
- Declare a character array
str[50]to hold the string. - Prompt the user for input.
- Use
scanf("%[^\n]", str)to read the input. - Print the stored sentence.
main.c
#include<stdio.h>
int main() {
char str[50];
printf("Enter a Sentence:\n");
scanf("%[^\n]", str);
printf("Sentence is:\n%s", str);
return 0;
}
Expected Output
Enter a Sentence: C was Developed in 1972. Sentence is: C was Developed in 1972.
Explanation of the Program
- By default, the standard
scanf("%s")stops reading as soon as it hits a whitespace character (like a space or tab). This makes it impossible to read a full sentence. - To fix this, we use the scanset specifier
%[^\n]. The^character means "NOT". So this command tells scanf to read everything until it encounters a newline (\n) character (which is generated when the user presses Enter).
Complexity
Time Complexity
O(n) - Where n is the length of the string being read.
Space Complexity
O(n) - Size of the character array.