String Comparison in C Programming

This snippet demonstrates how to read strings in C using two different methods: scanf with %s and fgets. It compares the strings inputted by the user and checks if they are equal or not. It also handles input buffer clearance and newline character removal for accurate comparison.
 avatar
unknown
c_cpp
6 months ago
700 B
3
Indexable
#include <stdio.h>
#include <string.h>

int main() {
    char str1[100], str2[100];
    
    // Input string using %s
    printf("Enter a string (using %%s): ");
    scanf("%s", str1);
    
    // Clear the input buffer before reading the next string
    getchar();

    // Input string character by character using fgets (to simulate %c input)
    printf("Enter the same string (using %%c): ");
    fgets(str2, sizeof(str2), stdin);
    
    // Remove the newline character if it exists
    str2[strcspn(str2, "\n")] = 0;

    // Compare strings
    if (strcmp(str1, str2) == 0) {
        printf("Strings are equal\n");
    } else {
        printf("Strings are not equal\n");
    }

    return 0;
}
Editor is loading...
Leave a Comment