简体   繁体   English

C 编程 - 不能多次调用函数

[英]C Programming - Cannot Call Function More Than Once

I'm having trouble calling the function more than one time in my C program.我在 C 程序中多次调用该函数时遇到问题。 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.我尝试将 strlen(x) 放在我的函数中的一个变量中,但我不太精通 C 语言,所以我决定将它排除在我的代码之外。

#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);
}

在此处输入图片说明

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编辑:要解决此问题,例如请参阅添加的 Ring Ø 评论并遵循建议

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM