-2
#include<stdio.h>

char str(char *s) {  
    char s1[100];
    printf("another string to replace:");
    scanf("%d",s1);  
    s=s1;  
    return s;
}

void main() {  
    char s[100],s2[100];  
    scanf("%s",s);  
    s2=str(s);  
    printf("%s",s);
}

How to return a string by replacing with another string in c??I'm unable to replace the string using functions

John Boker
  • 82,559
  • 17
  • 97
  • 130
Siri
  • 17
  • 4

2 Answers2

0

What you're going to want to do is copy the values of the characters in s1 into your s variable. not just set one equal to the other. either using strcpy or looping through your characters in s1 and copying them directly to the correct locations in s.

https://www.tutorialspoint.com/c_standard_library/c_function_strcpy.htm

this works for me without using strcpy:

#include<stdio.h>

void str(char *s) {  
    char s1[100];
    printf("another string to replace:");
    scanf("%s",s1);  
    // not real safe but we know s and s1 have 100 characters.
    for(int i = 0; i < 100; i++) {
        s[i] = s1[i];
    }   
}

int main() {  
    char s[100],s2[100];  
    scanf("%s",s);  
    str(s);  
    printf("%s",s);
}
John Boker
  • 82,559
  • 17
  • 97
  • 130
0

There a several things to say about your code.

  1. You can't copy strings using =

  2. The return type is wrong. Must be char*

  3. The scanf format string is wrong. Use %s for strings.

  4. You don't need an extra array in the function. Just scanf directly into s

  5. Never do scanf("%s", ... Always put a limit to it like scanf("%99s", ...

Something like:

char* str(char *s) {  
    printf("another string to replace:");
    scanf("%99s",s);  
    return s;
}

void main() {  
    char s[100],s2[100];  
    scanf("%99s",s);    
    strcpy(s2, str(s));  
    printf("%s",s);
}

I am, however, not sure what you want the code to do. As it is now s and s2 just end as identical strings.

If you just want a function that can read a new value into s it can be done like:

void str(char *s) {  
    printf("another string to replace:");
    scanf("%99s",s);  
}

void main() {  
    char s[100];  
    scanf("%99s",s);    
    str(s);
    printf("%s",s);
}
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63