【问题标题】:If statement being ignored in main function [duplicate]如果在主函数中忽略语句[重复]
【发布时间】:2015-07-11 09:20:57
【问题描述】:

我目前正在用 C 语言编写代码,而我在 main 函数中的 if 语句被忽略了。如您所见,此代码接收一些字符串作为输入并应用凯撒密码。注意:main中调用的函数ciphering也定义了,我只是不粘贴,因为我认为没有必要,因为问题是当我询问用户是否要加密或解密文本时,fgets if语句被完全忽略(在编写“加密”程序后退出)。 代码如下:

int main()
{
    char text[SIZE], choice[SIZE];
    printf("\nWelcome to Caesar's Cipher.\nDo you wish to encrypt or decrypt text?\n");
    fgets(choice, SIZE, stdin);
    if (strcmp(choice, "encrypt") == 0)
    { 
        printf("Insert text to encrypt:\n");
        fgets(text, SIZE, stdin);
        ciphering(text);
        printf("\nThis is your text encrypted with Caesar's Cipher:\n%s\n", text);
    }
    return 0;
}

【问题讨论】:

    标签: c if-statement fgets


    【解决方案1】:

    fgets 得到的字符串末尾有一个\n。需要手动删除,或者对比"encrypt\n"

    【讨论】:

      【解决方案2】:

      使用这个版本的strcmp()

      if (strncmp(choice, "encrypt", 7) == 0)
      

      问题在于 fgets 将换行符与您的字符串一起存储,因此要仅比较前 N 个字符并将 \n 排除在比较之外,请使用 strncmp 给出您的字符数想比较

      【讨论】:

      • @余浩谢谢。它奏效了。
      • if (strncmp(choice, "encrypt", 7) == 0) 也有效。谢谢。
      猜你喜欢
      • 1970-01-01
      • 2020-03-05
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 2012-06-03
      • 1970-01-01
      相关资源
      最近更新 更多