string editing and concatenation with user defined functions

Viewed 69

I'm carrying out a Pointer assignment for C language. The content of the task is to enter two strings within 100 characters, the first line contains the same or different strings, and the second line adds underbar to the space in the first string. I completed the code first and the code comparing the two strings works well, but the code that adds _ to the first string does not print the result. The limitation of this task is not to use string.h, and to use gets in the code where you enter two strings. Because strcmp should be used for comparing the two strings, but string.h cannot be used, I created a prototype of strcmp for the function that compares the two strings.

Here is my code:

#include <stdio.h>
int comparison(const char* one, const char* two) {
    for (; (*one != '\0') || (*two != '\0'); one++, two++) {
        if (*one != *two) {
            printf("two strings are different.");
            return -1;
        }
    }
    printf("two strings are same.");
    return 0;
}

void addUnderBar(char* str) {
    while (*str) {
        if (*str == ' ') {
            *str = '_';
        }
        ++str;
    }
}

int main(void) {
    char str1[100];
    char str2[100];

    printf("please input your first string");
    gets_s(str1, sizeof(str1));
    printf("please input your second string");
    gets_s(str2, sizeof(str2));

    comparison(str1, str2);
    addUnderBar(str1);
}
1 Answers

code that adds _ to the first string does not print the result

Because you are not printing the result. You just make this call:

addUnderBar(str1);

This function does not call printf like your other function does. It's better to keep a function for a specific task, so print the result after adding the underscore:

addUnderBar(str1);
printf("\n%s", str1);
Related