Strcmp —无输入时循环

语法

该程序执行以下操作:

  1. 扫描字符串char输入[15];
  2. 比较它与char password [] =“ 1sure”;
  3. 如果字符串不匹配则循环。
  4. 如果字符串匹配则终止。

字符串不匹配时,程序将循环运行。但是,我也希望程序在没有输入任何内容并且用户只是按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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章