1

所以我有这个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;
4

2 回答 2

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);
于 2012-12-02T18:54:54.313 回答
1

you can use getchar after scanf (also to clear 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);
于 2012-12-02T19:27:15.360 回答