繁体   English   中英

程序用C中的另一个字母替换一个字母

[英]Program to replace a letter with another in C

我编写了一个程序来替换字符串中的字母。 尽管没有错误,但是输出与预期不符。 请帮我。

#define _CRT_SECURE_NO_DEPRECATE
#include<stdio.h>
#include<string.h>
void replace(char s,char d);
char a[100];
int main()
{
    char b,r;
    printf("enter the string\n:");
    gets(a);
    printf("enter the the letter to be replaced\n:");
    scanf("%c", &b);
    printf("enter the letter to be replaced with\n:");
    scanf("%c", &r);
    replace(b,r);
}
void replace(char s, char d)
{
    int i,f=0;
    for (i = 0; a[i] != '\0'; i++)
    {
        if (a[i] == s)
        {
            a[i] = d;
            f = 1;
        }
    }
    if (f == 0)
    {
        printf("letter not found");
    }
}

输出量

enter the string
:hello every one
enter the the letter to be replaced 
:e
enter the letter to be replaced with
:letter not found

我想将e替换为o,但无法输入要替换的单词

更新使用scanf时,可以使用此循环摆脱输入缓冲区问题,但是我不确定如何在程序上实现它需要帮助

void
clear(void)
    {    
    while ( getchar() != '\n' )
        ;
    }

当您使用%s说明符读取字符串时, scanf()函数将跳过初始的空白字符,但是当您使用%c说明符读取char时,不会执行此操作。 您使用的gets()函数(永远不要使用过的函数)会读取换行符并将其丢弃。 因此,您对scanf()首次调用具有干净的输入流。 首次调用scanf()时, scanf()值读入变量b ,但尾随换行符将留在输入流中。 然后,当您尝试读取下一个值时, scanf()选择此换行符,而不是您要输入的值。

一种解决方法是像这样丢弃来自输入流的所有不需要的字符:

while (getchar() != '\n')
    continue;              // discard unwanted characters

如果确实要小心,也可以在条件表达式中测试EOF字符。 这种方法的优点是,无论用户在您的第二个提示符下输入多少个字符,都只会采用第一个,而换行符中其余的字符将被丢弃。 由于输入流中没有剩余内容,因此scanf()必须等待用户在您的第三个提示符下输入内容。 您应在每次调用scanf()之后放置此代码,以确保输入流清晰可见。

现在, gets()是一个可怕且不安全的函数,它请求缓冲区溢出,因为它不会检查是否为正在获取的字符串分配了足够的内存。 而是使用fgets() 此函数采用一个参数,该参数指定要读取的最大字符数,包括空终止符。 fgets()还将换行符读入字符串,因此,如果您不想要它,则必须自己处理。 这是您需要进行的修改:

int i = 0;
...
char b,r;
printf("enter the string\n:");
fgets(a, 100, stdin);

while(a[i] != '\n' && a[i] != '\0')  // remove newline
    ++i;
a[i] = '\0';

printf("enter the the letter to be replaced\n:");
scanf("%c", &b);
while (getchar() != '\n')
    continue;              // discard unwanted characters

printf("enter the letter to be replaced with\n:");
scanf("%c", &r);
while (getchar() != '\n')
    continue;              // discard unwanted characters

replace(b,r);
printf("%s\n", a);
...

我添加了一个最终的printf()来显示更改后的字符串。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM