C 中的简单循环和字符串长度

Simple Loops and String Length in C

我是 C 的新手。在 Visual Studio 2015 年写作时,我试图通过使用 fgets 安全地提示用户输入字符串。我想使用 fgets 获取字符串,检查字符串是否太长,如果太长则重新提示用户,直到他们输入正确的字符串。这是我的代码

/*
* Nick Gilbert
* COS317 Lab 2 Task 2
*/
#include "stdafx.h"
int main()
{
    char str[10];
    int isValid = 0;
    while (isValid == 0) {
        printf("Please enter a password: ");
        fgets(str, 10, stdin);
        if (strlen(str) == 9 && str[8] != '\n') { //
            printf("Error! String is too long\n\n");
            memset(&str[0], 0, sizeof(str));
        }
        else {
            printf(str);
            isValid = 1;
        }
    }
    printf("Press 'Enter' to continue...");
    getchar();
}

但是,当我 运行 输入一个错误的字符串时,多余的字符会自动输入到下一个 fgets 中!

我怎样才能解决这个问题,让它做我想做的事?

如果fgets读入的字符串不以换行符结尾,循环调用fgets直到它结束,然后再次提示用户。

    if (strlen(str) > 0 && str[strlen(str)-1] != '\n') {
        printf("Error! String is too long\n\n");
        do {
            fgets(str, 10, stdin);
        } while (strlen(str) > 0 && str[strlen(str)-1] != '\n') {
    }

此外,切勿在第一个参数处将变量传递给 printf,尤其是当该变量的内容来自用户输入的数据时。这样做会导致 format string vulnerability.

试试这个:

#include "stdafx.h"
int main()
{
    char str[10];
    int isValid = 0;
    while (isValid == 0) {
        printf("Please enter a password: ");
        fgets(str, str, stdin);
        if (strlen(str) == 9 && str[8] != '\n') { //
            printf("Error! String is too long\n\n");
            memset(str, 0, sizeof(str));
        }
        else {
            printf("%s",str);
            isValid = 1;
        }
    }
    printf("Press 'Enter' to continue...");
    getchar();
}

另外:

在使用 memset() 时,您可以直接使用 array_name 而不是 &array_name[0]