[英]'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;
}
很感謝任何形式的幫助:)
我假設您希望用戶在循環開始之前定義一次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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.