C Programming

⌘K
  1. Home
  2. Docs
  3. C Programming
  4. Arrays and Strings
  5. Reading and Writing Strings in C

Reading and Writing Strings in C

  • Using scanf() (single word only):
char str[20];
scanf("%s", str);  // Stops reading at whitespace
  • Using gets() (reads whole line):
char str[50];
gets(str);  // Deprecated but allows spaces
  • Using fgets() (safe alternative):
fgets(str, sizeof(str), stdin);
  • Using printf():
printf("%s", str);
  • Using puts():
puts(str);  // Adds newline automatically

The null character is used to terminate a string in C. Without it, functions like printf() would not know where the string ends.

char s[] = "Hi";  // Actually stored as {'H', 'i', '\0'}

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *