代码C:输入字符串,不允许输入特殊字符,例如@

时间:2020-07-09 03:33:15

标签: c

char getText() {
    char text[100];
    int c = 0;
    do {
        __fpurge(stdin);
        printf("Enter text: ");
        gets(text);
        while (text[c] != '\0') {
            if ((text[c] != '@')) {
                if (text[c] == '@') {
                    printf("Contain @\n");
                }
            } else break;
            c++;
        }
    } while (1);
    return text;
}

我有此功能,请检查用户输入的输入字符串。如果字符串包含“ @”。要求用户再次输入
如果字符串不包含“ @”。接受字符串并返回字符串。
但是我无法中断循环。任何人都可以帮助我解决问题。首先谢谢。

1 个答案:

答案 0 :(得分:0)

确切的文字:

while (text[c] != '\0') {
    if ((text[c] != '@')) {
        if (text[c] == '@') {
            printf("Contain @\n");
        }
    } else break;
}

text[c]不等于@时,遵循的条件告诉编译器比较text[c]@,这毫无意义。

尝试一下:

while (text[c] != '\0') {
    if (text[c] == '@') printf("Contain @\n");
    else break;
    // ...
}

另外,请记住,使用gets()是危险的learn how & why

您可能更愿意使用fgets()

fgets(text, MAX, stdin); // #define MAX 100, playing with magical numbers
                         // isn't considered good
相关问题