TutorialStudyMite

Strings in c gets(), fgets(), getline(), getchar(), puts(), putchar(), strlen()

PPooja Rao4 min read
Beginner friendly

Track completion, mastery, and revision.

Table of Contents

1. Introduction to Strings

2. Memory Representation

3. Reading Strings

   - Using scanf()

   - Using gets()

   - Using fgets()

   - Using getline()

   - Using getdelim()

   - Using getchar()

4. Printing Strings

   - Using printf()

   - Using puts()

   - Using putchar()

   - Using sprintf()

5. String Operations

Introduction to Strings

1. An array of characters is called a string.

2. Strings are used to manipulate text or sentences.

3. Real-world applications include:

   - Spell checkers

   - Spam filters

   - Search engines

   - Bioinformatics

   - Digital forensics

Strings in C

1. Strings are terminated by a null character '\0'.

2. Syntax:


   char string_name[] = "text";

   ```

3\. Example:

```c

   char greeting[] = "Hello World";

   ```

   - The null character is added automatically

   - This is called a string constant

Alternative declarations:

```c

char greeting[12] = {'H','e','l','l','o',' ','W','o','r','l','d','\0'};

or


char name[size];  // Can store size-1 characters + null

Memory Representation

Example:


char word[] = "Hello";

| Index | 0 | 1 | 2 | 3 | 4 | 5 |

|-------|---|---|---|---|---|---|

| Char  | H | e | l | l | o | \0|

| Address|1000|1001|1002|1003|1004|1005|

  • Each character occupies 1 byte

  • word[1] accesses 'e' at address 1001

Reading Strings

1. Using scanf()


scanf("%s", str);

  • Stops reading at whitespace

  • No & needed for strings

  • Null character automatically appended

2. Using gets() (Deprecated)


gets(str);

  • Reads entire line including spaces

  • Dangerous - no buffer overflow protection

  • Avoid using in new code

3. Using fgets()


fgets(str, size, stdin);

  • Safer than gets()

  • Reads up to size-1 characters

  • Includes newline character


size_t getline(char **lineptr, size_t *n, FILE *stream);

Example:


#include <stdio.h>

#include <stdlib.h>

int main() {

    char *buffer = NULL;

    size_t size = 0;

    ssize_t chars_read;

    printf("Enter string: ");

    chars_read = getline(&buffer, &size, stdin);

    if(chars_read != -1) {

        printf("You entered: %s", buffer);

        printf("Buffer size: %zu\n", size);

    }

    free(buffer);

    return 0;

}

  • Dynamically allocates memory

  • Handles any input size safely

5. Using getdelim()


getdelim(&buffer, &size, delimiter, stream);

  • General version of getline()

  • Can specify any delimiter character

6. Using getchar()


char ch;

int i = 0;

while((ch = getchar()) != '\n') {

    str[i++] = ch;

}

str[i] = '\0';

  • Reads one character at a time

  • Must manually add null terminator

Printing Strings

1. Using printf()


printf("%s", str);

  • Most flexible method

  • Supports formatting

2. Using puts()


puts(str);

  • Automatically adds newline

  • Simple but less flexible

3. Using putchar()


for(int i=0; str[i]!='\0'; i++) {

    putchar(str[i]);

}

  • Prints one character at a time

4. Using sprintf()


char buffer[100];

sprintf(buffer, "Formatted %s", str);

  • Stores formatted output in buffer

  • Risk of buffer overflow

String Operations

Calculating String Length

Method 1: Manual Calculation


int length = 0;

while(str[length] != '\0') {

    length++;

}

Method 2: Using strlen()


#include <string.h>

int len = strlen(str);

Example Programs:


// Using gets() (not recommended)

#include <stdio.h>

int main() {

    char str[100];

    printf("Enter string: ");

    gets(str);  // Warning: deprecated

    printf("Length: %d\n", strlen(str));

    return 0;

}

// Using fgets()

#include <stdio.h>

#include <string.h>

int main() {

    char str[100];

    printf("Enter string: ");

    fgets(str, sizeof(str), stdin);

    str[strcspn(str, "\n")] = '\0';  // Remove newline

    printf("Length: %zu\n", strlen(str));

    return 0;

}

Finished reading?

Was this helpful?

Your feedback shapes better tutorials for everyone.