我有这个程序要求用户输入一个字符串和两个字符。一个要替换的角色,另一个将替换旧的角色。我调用一个名为replace()
的函数循环遍历字符串,查找旧字符并将其替换为新字符。它在main()
中打印新字符串,但它不能正常工作。我做错了什么?
#include <stdio.h>
#include <string.h>
void replace(char string[], char old, char new);
int main()
{
char input[100], newChar, oldChar;
char newstr[100];
printf("Enter a string: ");
fgets(input, 100, stdin);
printf("Enter a character to replace: ");
scanf("%c", &oldChar);
printf("Replace character with?: ");
scanf("%c", &newChar);
getchar();
replace(input, oldChar, newChar);
printf("Result: %s\n", input);
}
void replace(char string[], char old, char new)
{
int length = strlen(string);
int i = 0;
for(i=0; i<length; i++)
{
if(string[i] == old)
{
string[i] = new;
}
}
}
答案 0 :(得分:1)
请试试这个,我认为缺少了getchar:
printf("Enter a character to replace: ");
scanf("%c", &oldChar);
getchar();
printf("Replace character with?: ");
scanf("%c", &newChar);
getchar();