该程序执行以下操作:
字符串不匹配时,程序将循环运行。但是,我也希望程序在没有输入任何内容并且用户只是按Enter时循环执行。我尝试使用一个isgraph
函数,但这会导致程序崩溃。我在代码中注释了该部分。如果没有输入,有人可以建议如何使程序循环吗?
#include <stdio.h>
#include <string.h>
int main()
{
char password[] = "1sure";
char input[15];
do
{
printf("Password: ");
scanf("%s", input);
if(strcmp(password,input)==0)
{
printf("Password accepted.");
putchar('\n');
return(0);
}
/*else if(isgraph(input)==0)
{
printf("No input detected."); //Program crashes with this segment.
continue;
}*/
else
{
printf("\nInvalid password.\n");
continue;
}
}
while(1);
}
该程序可能如下所示
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main( void )
{
char password[] = "1sure";
char input[15];
do
{
printf("\nPassword: ");
if ( fgets( input, sizeof( input ), stdin ) == NULL )
{
printf( "An error occured or input was interrupted\n" );
return 0;
}
size_t n = strlen( input );
while ( n && isspace( input[n-1] ) ) input[--n] = '\0';
if ( input[0] == '\0' )
{
printf("No input detected.\n");
continue;
}
else if( strcmp( password, input ) == 0 )
{
printf("Password accepted.\n");
return(0);
}
else
{
printf("\nInvalid password.\n");
continue;
}
} while(1);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句