簡體   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