简体   繁体   English

即使使用命令 if(*str == 'stop') 并输入 stop,'While' 循环也不会停止

[英]'While' loop does not stop even with the command if(*str == 'stop') and entering stop

I want to write a function that replaces all occurrences of a character c with a character e.我想写一个 function 用字符 e 替换所有出现的字符 c。 The functions seems to be working.这些功能似乎正在发挥作用。 However in the main, I want to be able to repeatedly enter a string, scan the character to be replaced, scan the character that will replace, and print the before and after, UNTIL the entered string is 'stop'.但是主要是,我希望能够重复输入一个字符串,扫描要替换的字符,扫描要替换的字符,并打印前后,直到输入的字符串是“停止”。 How do i do this?我该怎么做呢? I have tried defining 'stop' as a constant character string but that did not work.我尝试将“停止”定义为常量字符串,但这不起作用。 This is what my code looks like:这就是我的代码的样子:

#include <stdio.h>
#include <string.h>

void replaceAll(char *str, char c, char e){
     for(int i = 0; str[i] != '\n'; i++){
        if(str[i] == c){
        str[i] = e;
        }
     }
     return; 
}

int main(){
    char str[80], c, e;
    //repeatedly enter string;
    while(*str != '\n'){
        fgets(str, sizeof(str), stdin);
        //jump out of loop
        if(*str == 'stop')
        getchar();
        scanf("%c", &c);
        getchar();
        scanf("%c", &e); 

        printf("replace all occurances of %c with %c in\n", c, e);
        printf("%s", str);
        //calls function
        replaceAll(str, c, e);
        printf("%s", str);
    }
    return 0; 
}

Any help is very much appreciated:)很感谢任何形式的帮助:)

I assume you want the user to define c and e once before the loop starts.我假设您希望用户在循环开始之前定义一次ce Then move the following code to anywhere before the while loop starts.然后将以下代码移动到while循环开始之前的任何位置。 Best if you inform the user what to enter and not just use scanf() .最好告诉用户要输入什么,而不仅仅是使用scanf()

    printf(“please enter the char to find\n”);
    getchar();
    scanf("%c", &c);
    printf(“please enter the char to replace\n”);
    getchar();

    scanf("%c", &e); 

The main problem is with the following line:主要问题在于以下行:

// jump out of loop
if(*str == 'stop')

First, a single bracket is used for single characters and not for strings, where you should use brackets (“).首先,单个括号用于单个字符而不是字符串,您应该使用括号(“)。

Second, use strcmp ().二、使用strcmp ()。

Third, to jump out of the loop, use break;三、跳出循环,使用break; . .

// jump out of loop
if(strcmp (&str[0], “stop\n”) == 0)
{
      break;
}

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

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