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"

These are three methods for getting input from the user:-
  1. scanf() -> We can input string by two ways with scanf() method:

    1. 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

    2. 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

  2. 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

  3. fgets() -> It checks the array bound and keeps on reading until "\n" newline character encountered or maximum limit of n-1 where n is integer parameter fgets method.

    Syntex: 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

Comments

Post a Comment