String input in c (with example)
A string is an array of characters in c, the string is written under the double quotes only. Even though any numeric or single alphabetical character written under the double quotes, all are considered as a string.
Example: char str[] = "programz1000"
-
scanf() -> We can input string by two ways with scanf() method:
-
Syntex:
scanf("%s",string)
Example:
#include<stdio.h> int main(){ char str[20]; scanf("%s",str); printf("%s",str); return 0; }
Input: Programz rocks
Output:Porgramz
Note: In this program, It doesn't accept string after first space
-
Syntex:
scan("%[^\n]*c,string)
Example:
#include<stdio.h> int main(){ char str[20]; scanf("%[\n]*c",str); printf("%s",str); return 0; }
Input: Programz rocks
Output: Porgramz rocks
-
Syntex:
-
gets() -> gets() method take input from user till new line is reached i.e user presses enter. this method has been removed from C11 so it may generate warning or error.
Syntex:gets(string)
Example:
#include<stdio.h> int main() { char str[20]; gets(str); printf("%s",str); return 0; }
Input: Programz rocks
Output: Porgramz rocks
-
fgets() -> It checks the array bound and keeps on reading until "\n" newline character encountered or maximum limit of
Syntex:n-1
where n is integer parameter fgets method.char *fgets(char *str, int n, FILE *stream)
Example:
#include<stdio.h> int main() { char str[20]; fgets(str,20,stdin); printf("%s",str); return 0; }
Input: Programz rocks
Output: Porgramz rocks
well done.
ReplyDelete