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') { //http://stackoverflow.com/questions/21691843/how-to-correctly-input-a-string-in-c 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 ,特别是如果该变量的内容来自用户输入的数据。 这样做可能会导致格式字符串漏洞 。

试试这个:

 #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') { //http://stackoverflow.com/questions/21691843/how-to-correctly-input-a-string-in-c 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]