我想编写一个函数,用字符 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;
}
非常感谢任何帮助:)
最佳答案
我假设您希望用户在循环开始之前定义c和e一次。 然后将以下代码移动到 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/