在这个程序中,为什么getchar()结束我的循环

时间:2018-04-07 04:49:41

标签: c arrays c-strings getchar

在main函数中,如果我只是声明这样的替换字符..

c = '*';

程序将保持循环正常并在用户输入y或Y后继续正常工作。

但是,如果我希望用户输入替换字符并执行此操作..

c = getchar();

用户输入y或Y后,循环结束,程序关闭。 这是为什么?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define BUFF_SIZE 512


void getRandomStr(char s1[]);
void strreplace(char s1[], char chrs[], char c);
void check(char s2[], char chrs[]);
char cont(void);

int main()
{
    char s1[BUFF_SIZE];
    char s2[BUFF_SIZE], c;
    char proceed = 0;


    do {

        getRandomStr(s1);
        printf("Your random string is: %s\n", s1);


        /* gets(s1) */
        printf("\nPlease enter up to 20 letters to be replaced: ");
        gets(s2);
        printf("\nPlease enter a replacement character (Ex. *, $, etc.): ");
        c = getchar();


        check(s1, s2);


        printf("\nModified string after replacement is: ");
        strreplace(s1, s2, c);


        proceed = cont();

    } while (proceed == 'Y' || proceed == 'y');

}


void getRandomStr(char s1[]) {

    int i;

    srand(time(NULL));
    for (i = 0; i < 41; i++) {

        char c = rand() % 26 + 'A';
        s1[i] = c;

    }

    s1[41] = '\0';
}

void strreplace(char s1[], char chrs[], char c)
{
    int i = 0;

    while (chrs[i] != '\0') {

        for (int j = 0; s1[j] != '\0'; j++) {

            if (s1[j] == chrs[i])
            {

                s1[j] = c;

            }
        }

        i++;
    }
    puts(s1);
}


char cont()
{

    char proceed;
    printf("\nWould you like to run the program again (y/n)? ");
    scanf_s("%c%*c", &proceed);
    return proceed;
}

void check(char s2[], char chrs[])
{
    int i = 0;

    while (chrs[i] != '\0') {

        for (int j = 0; s2[j] != '\0'; j++) {

            if (!(chrs[i] >= 'A' && chrs[i] <= 'Z'))
            {

                printf("An invalid character was entered.\n");
                break;
            }
        }

        i++;
    }
} 

0 个答案:

没有答案