String Examples

/*** simple declaration and input using scanf() ***/
#include <stdio.h>
#include <string.h>

int main(void)
{
  char name[5] = "John";
  char day[4] = {'W', 'e', 'd', '\0'};

  printf("\n%s %s \n", name, day);

  name[1] = 'a';
  name[2] = 'y';
  printf("\n%s %s\n", name, day);

  name[3] = '\0';
  printf("\n%s %s\n", name, day);

  printf("\nEnter a string no longer than 3 characters ");
  scanf("%s", day);

  printf("\n%s %s\n", name, day);

  return (0);
}



/*** problems and differences with scanf() and gets() ***/ #include <stdio.h> #include <string.h> int main(void) { char stream[80], name[5]; printf("\nEnter a name "); scanf("%s", name); gets(stream); printf("\nname = %s\nrest = %s\n", name, stream); return (0); }
/*** using gets() and sscanf() ***/ /*** NOTE: scanf(), sscanf(), and fscanf() all behave identically scanf() gets input from standard input (keyboard) sscanf() gets input from a designated string fscanf() gets input from a designated external file ***/ #include <stdio.h> #include <string.h> int main(void) { char stream[80], name[5]; int temp; float test; printf("\nEnter a name integer and a float "); gets(stream); sscanf(stream, "%s %d %f", name, &temp, &test); printf("\nstream = %s", stream); printf("\nname = %s int = %d float = %f\n", name, temp, test); return (0); }