该程序执行以下操作:
- 扫描文本字符串char input[15];
- 将其与字符密码[ ] = "1sure";进行比较
- 如果字符串不匹配则循环。
- 如果字符串匹配则终止。
当字符串不匹配时程序会循环。但是,我还希望程序在没有输入任何内容的情况下循环并且用户只需按 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);
}
关于c - Strcmp — 无输入时循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29203453/