繁体   English   中英

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

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

我想写一个 function 用字符 e 替换所有出现的字符 c。 这些功能似乎正在发挥作用。 但是主要是,我希望能够重复输入一个字符串,扫描要替换的字符,扫描要替换的字符,并打印前后,直到输入的字符串是“停止”。 我该怎么做呢? 我尝试将“停止”定义为常量字符串,但这不起作用。 这就是我的代码的样子:

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

很感谢任何形式的帮助:)

我假设您希望用户在循环开始之前定义一次ce 然后将以下代码移动到while循环开始之前的任何位置。 最好告诉用户要输入什么,而不仅仅是使用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); 

主要问题在于以下行:

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

首先,单个括号用于单个字符而不是字符串,您应该使用括号(“)。

二、使用strcmp ()。

三、跳出循环,使用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