扫描字符串时,如果用户输入超过30个字符,如何不允许输入?

时间:2012-12-02 18:48:19

标签: c

所以我有这个scanf

scanf ("%30[^\n]%c", &i

如何添加一个条件,如果用户输入超过30个字符,它会提示一条消息,说明字符太多并让它们重新输入?

这是我的整个循环,以便在输入正确但我没有正确的条件设置之前保持重新进入

int keeptrying = 1, rc;
char after, i;

do
{
    rc = scanf ("%30[^\n]%c", &i, &after);
        if (rc == 0)
        {
            printf (" **Invalid input try again: ");
            clear();
        }
            else if (after != '\n')
            {
                printf (" **Trailing characters try again: ");
                clear();
            }
                else if () // THIS IS WHERE I WOULD PUT THE CONDITION
                {
                    printf (" **Title is longer than 30 characters: ");
                }
                    else
                    {
                        keeptrying = 0;
                    }

} while (keeptrying == 1);

return i;

2 个答案:

答案 0 :(得分:1)

基本上,你只想阅读一行,并检查它的长度是否大于30.要做到这一点,你使用strlen()来阅读我推荐使用类似的东西getline代替:

int keeptrying = 1;
char *line = NULL;
size_t linecap = 0;

do {
    ssize_t rc = getline(&line, &linecap, stdin);
    if (rc == 0)
    {
        printf ("End of file.");
        exit(1);
    }
    else if (strlen(line) > 30)
    {
        printf (" **Title is longer than 30 characters: ");
    }
    else
    {
        keeptrying = 0;
    }
} while (keeptrying == 1);

// Use line

free(line);

答案 1 :(得分:1)

你可以在scanf之后使用getchar(也用于清除stdin):

do
{
    char i[31];
    rc = scanf ("%30[^\n]", &i);
        if (rc == 0)
        {
            printf (" **Invalid input try again: ");
            clear();
        }
            else if (getchar() != '\n')
            {
                printf (" more than 30 characters try again: ");
                clear();
            }
                    else
                    {
                        keeptrying = 0;
                    }

} while (keeptrying == 1);