【问题标题】:C Vigenere Cipher Not PrintingC Vigenere 密码不打印
【发布时间】:2017-01-23 01:11:08
【问题描述】:

我的任务是创建一个 vigenere 密码,但我的程序没有打印出任何内容。问题是,我不确定问题出在哪里;文件没有读入,我的逻辑不正确,等等?任何关于我搞砸的地方的帮助表示赞赏。

#include <stdio.h>
#include <string.h>
#include <ctype.h>

void encrypt(char *theString, int shift)
{

    if (isalpha(*theString) && isupper(*theString))
    {

            *theString += shift;
            if (*theString >= 'Z')
            {
                    *theString = *theString - 26;
            }


    }

    theString++;

}


int main(void)
{

    FILE *inputFile;
    char KEY[256];
    char theString[80];
    int shift;
    int i;

    inputFile = fopen("code.txt", "r");
    if (inputFile == NULL)
    {
            printf("Failed to open\n");

            return(0);

    }
    fgets(theString, sizeof(theString), stdin);

                   printf("Enter the Key: ");
    fgets(KEY, sizeof(KEY), stdin);
    for (i = 0; i < 256; i++)
    {

            shift = KEY[i] - 65;
            encrypt(theString,shift);
            puts(theString);
    }
    return(0);


}

【问题讨论】:

    标签: c encryption vigenere


    【解决方案1】:

    您没有看到任何输出的原因是因为这首先发生:

    fgets(theString, sizeof(theString), stdin);
    

    从标准输入中读取一个字符串,然后等到你按下 输入。所以看起来程序卡住了。你应该 先打印一个提示,如:

    printf("Enter a string: ");
    

    【讨论】:

      【解决方案2】:

      您的encrypt 循环仅修改输入字符串的第一个字符。您需要一个循环来修改每个字符:

      void encrypt(char *theString, int shift)
      {
          for ( ; *theString != '\0'; theString++)
          {
              if (isupper(*theString))
              {
                  *theString += shift;
                  if (*theString >= 'Z')
                  {
                      *theString = *theString - 26;
                  }
      
              }
          }
      }
      

      其他要点:

      • isupper() 暗示 isalpha();两者都不需要
      • fgets() 出错时返回 NULL;你应该检查一下

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-25
        相关资源
        最近更新 更多