在 C 语言的替换程序中成功进行初始输入后,无法输入第二个输入

标签 c arrays string

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

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

输出 = BD*FK*L

该程序基于循环,并询问您是否要输入另一个字符串进行替换。当我输入 '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);
}

最佳答案

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

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

关于在 C 语言的替换程序中成功进行初始输入后,无法输入第二个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13131722/

相关文章:

c++ - 为什么编译器不为类内声明的变量分配内存?

c - 从 yylex 返回 "non-ints"

C - 通过引用传递已知大小的多维数组

arrays - 从数组中的文本变体分配图像

string - 与字符串操作不同

c - 在 OpenMP while 循环中手动同步

c - C++中的private成员变量如何在C中模拟?

c++ - 在字符串类型崩溃的动态数组中实现删除

java - ''s cannot be resolved' ' 如何解决此错误?

c - 给定参数反转字符串