0

I'm having trouble calling the function more than one time in my C program. The gist of the assignment is to replace the whitespaces in a sentence inputted from the user and replace it with a different character. For some reason, the program will call the same first function multiple times. I tried putting the strlen(x) in a variable inside my function, but I'm not very well versed in the C language, so I decided to leave it out of my code.

#include <string.h>

void display(char x[], char y);

void main(){
    //Do not change this function
    char a[100];
    printf("Enter a sentence\n");
    gets(a);
    display(a, '*');        //To replace every space by *
    display(a, '-');        //To replace every space by -
    display(a, '+');        //To replace every space by +
}

void display(char x[], char y){
    for(char i = 0; i < strlen(x); i++) {
        if(x[i] == ' ') {
            x[i] = y;
        }
    }
    printf("%s\n", x);
}

enter image description here

6
  • Welcome to SO! Please don't post images of code/output. Instead of overwriting the spaces in your loop, just print each character directly, making the substitution as needed. Hopefully the next lesson is how to run a buffer overflow attack on this application. Commented Dec 9, 2019 at 3:02
  • 2
    Copy the original string in a buffer before you call display(), like char buf[100]; ... strcpy(buf, a); display(buf, '*');strcpy(buf, a); display(buf, '-');... Commented Dec 9, 2019 at 3:16
  • Use fgets instead of gets, which is a huge security vulnerability Commented Dec 9, 2019 at 3:48
  • the posted code does not compile! amongst other things, the statement: #include <stdio.h> is missing (and needed for the calls to printf() Commented Dec 10, 2019 at 3:22
  • regarding: gets(a); The function: gets() has been depreciated for many years and (recently) completely removed from the C standard. Strongly suggest using: fgets() (which has a different parameter list, see the MAN page for details Commented Dec 10, 2019 at 3:23

1 Answer 1

3

It does not "call the same first function". You change the value of your string inside the function, so after the first run of the function the string does not have spaces. Therefore the second and third call print the string unchanged:

void display(char x[], char y){
    for(char i = 0; i < strlen(x); i++) {
        if(x[i] == ' ') {
           // this happens only upon first call! 
           x[i] = y;
       }
    }
    printf("%s\n", x);
}

Edit: to fix the issue, for example see the comment Ring Ø added and follow the advice

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.