0

我正在编写一个程序来生成一串随机大写字母,然后获取用户输入的大写字母以及用户的字符。对于随机字符串中用户输入字母的任何实例,它会将该字母替换为用户输入的字符。

例如,s1 = {BDHFKYL} s2 = {YEIGH} c = '*'

Output = BD*FK*L

该程序基于一个循环,并询问您是否要输入另一个字符串来替换。当我输入 a'y'进入另一个循环时,我得到了这个:

Please enter at least 2 capital letters and a maximum of 20.

HAJSKSMDHSJ

HAJSKSMDHSJ

NWLRBB*QB*C**RZOW**Y*I**Q*C*XR**OWFRX**Y

Would you like to enter another string?

y          -(HERE"S WHERE THE PROBLEM IS)-

Please enter at least 2 capital letters and a maximum of 20.

You need at least two letters

Would you like to enter another string?

有什么建议么?先感谢您。

void fillS1(char x[]);

void fillS2(char x[], char y[], char z);

void strFilter(char a[], char b[], char c);

int main(int argc, const char * argv[])
{
    char s1[42];
    char s2[22];

    fillS2(s2, s1, '*');

    return 0;
}

void fillS1(char x[])
{
    for (int i = 0; i < 40; i++)
        x[i] = 'A' + random() % 26;
    x[40] = (char)0;
}

void fillS2(char x[], char y[], char z){
    char loopContinue = 0;

    do {

        int i = 0;

        printf("Please enter at least 2 capital letters and a maximum of 20.\n");
        while (( x[i] = getchar()) != '\n' ) {
            i++;
        }

        x[i] = '\0';

        if (i < 3) {
            printf("You need at least two letters\n");
        }
        else if (i > 21){
            printf("You cannot have more than twenty letters\n");
        }
        else if (i > 0){
            for (i = 0; i < 20; i++) {
                if ((x[i] >= 'A') && (x[i] <= 'Z')) {
                    puts(x);

                    fillS1(y);

                    strFilter(y, x, '*');
                    break;
                }
            }
        }

        printf("Would you like to enter another string?\n");
        scanf("%c", &loopContinue);

    } while (loopContinue != 'n');

}

void strFilter(char a[], char b[], char c){
    int i = 0;
    int n = 0;

    while (n < 20) {
        for (i = 0; i < 40; i++) {
            if (a[i] == b[n]){
                a[i] = c;
            }
        }
        i = 0;
        n++;
    }

    puts(a);
}
4

3 回答 3

0

混合scanfgetchar对我来说似乎是个坏主意。为什么不也用它getchar来确定用户是否表示他们想继续呢?(并且不要忘记处理大小写。)

您可能想阅读文章Get scanf to quit when it reads a newline?

于 2012-10-30T01:02:00.137 回答
0

当您使用:

    scanf("%c", &loopContinue);

它只是读取字母,而不是用户在它之后键入的换行符。当您回到循环顶部时,第一个getchar()读取仍在等待处理的换行符。

当您收到此问题的回复时,您需要阅读整行,而不仅仅是单个字符。

于 2012-10-30T01:10:34.233 回答
0

尝试使用 memset() 清除 x、y 和 z

于 2012-10-30T03:25:52.197 回答