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

标签 c string loops while-loop

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

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

关于c - 即使使用命令 if(*str == 'stop' ) 并输入 stop,“While”循环也不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58160518/

相关文章:

java - 理解这个递归函数

c - 重新分配()失败

c++ - NULL 函数指针

c - 是否有像 gccxml 这样的用于包装器生成的 C header 解析器工具?

c# - 如何在字符串中的特定位置插入值c#

c - C 中的指针和字符串

python - 嵌套字典的划分

c - 英特尔编译器忽略了大循环?

python将字符串转换为运算符

python - 提高嵌套循环性能