c - Strcmp — 无输入时循环

标签 c loops strcmp c-strings

该程序执行以下操作:

  1. 扫描文本字符串char input[15];
  2. 将其与字符密码[ ] = "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);
}

关于c - Strcmp — 无输入时循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29203453/

相关文章:

c - 串行编程 : Sender and Receiver

c - 使用指针打印值

c - 使用 strcmp() 从客户端读取数据未按预期工作

javascript - 每个循环中未定义的项目

c - 为什么使用 strcmp 会出现段错误

c - 返回 char * 值

c - 为什么这些构造使用增量前和增量后未定义的行为?

c - 尝试实现一个从用户那里获取功能的通用链表

python - 如何在python中创建一个每天枚举的循环?

php - 数组 PHP 的排列