how to input string in c code example

Example 1: getting string input in c

#include<stdio.h>
#include<conio.h>
void main(){
chat sam[10];
clrscr();
printf("ENTER STRING NAME :");
gets(s);
printf("STRING :%s",s);
getch();
}

Example 2: input output string in c

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() 
{

    /* Enter your code here. Read input from STDIN. Print output to STDOUT */
    char ch;
    char s[100];
    char p [100];
    scanf("%c", &ch);
    scanf("%s", s);
    scanf("\n");
    scanf("%[^\n]%*c", p);
    
    printf("%c \n", ch);
    printf("%s \n", s);
    printf("%s", p);
    return 0;
}

Example 3: string in c

#include <stdio.h>
void displayString(char str[]);

int main()
{
    char str[50];
    printf("Enter string: ");
    fgets(str, sizeof(str), stdin);             
    displayString(str);     // Passing string to a function.    
    return 0;
}
void displayString(char str[])
{
    printf("String Output: ");
    puts(str);
}

Example 4: read string c

char name[20];
scanf("%s", name);

Example 5: string in c

#include <stdio.h>

int main() {
  char *str1 = strdup("Hello");
  char *str2 = malloc(sizeof(char) * (strlen(str1) + 1));
  
  for (int i = 0; i < strlen(str1); ++i)
    str2[i] = str1[i];
  str2[strlen(str1)] = '\0'; // very important, the string stop to print
  printf("%s --> %s\n", str1, str2);
}

Tags:

Css Example