首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C语言:在输出的最后一个字符之后有一个尾随字符

C语言:在输出的最后一个字符之后有一个尾随字符
EN

Stack Overflow用户
提问于 2015-09-24 04:35:59
回答 3查看 167关注 0票数 1

我正在为我的实验室工作表制作一个凯撒密码,并使它能够加密3次加密(凯撒的密码),这是练习的重点。但有一件事困扰着我。首先,如果我把它放在3之外,就会有一个尾随字符。例如,输入"malware",然后输入2表示键。这是我的密码:

代码语言:javascript
运行
复制
#include<stdio.h>
#include<stdlib.h>

int main()
{
   char text[100];
   int key,i;

   printf("Please enter a word/sentence (lowercaps) for encrypting :\n ");
   fgets(text,100,stdin);
   printf("Please enter the key that you desire : eg:14\n");
   scanf("%d", &key);
   for(i=0;i<strlen(text);i++)
   {
      if (key>=26)
      {
         key=key%26;
      }
      if (text[i]==' ')
      {
         continue;
      }
      if(text[i]+key>'z')
      {
         text[i]-=97;
         text[i]+=26;
         text[i]+=key;
         text[i]%=26;
         text[i]+=97;
      }
      else
      {
         text[i]=text[i]+key;
      }
   }

   printf("this is your encrypted text : %s", text );
}

我希望我遵循正确的缩进编码方法。所以有很多不喜欢的地方

EN

Stack Overflow用户

发布于 2015-09-24 05:21:19

我将简化并更正这段代码

代码语言:javascript
运行
复制
#include <stdio.h>

int main() {
    char text[100];
    int key, i;
    printf("Enter a word / sentence (lowercaps) for encrypting : ");
    fgets(text, 100, stdin);
    printf("Enter the key that you desire (eg. 14) : ");
    scanf("%d", &key);
    key %= 26;    // Pull this out of the loop and remove the unnecessary if
    for (i = 0; text[i]; ++i) {    // Correct the loop condition
        if (text[i] == ' ') continue;
        if (text[i] + key > 'z')
            text[i] = (text[i] - 97 + 26) % 26 + 97;    // Simplify
        else
            text[i] += key;
    }
    printf("Encrypted text : %s\n", text);
    return 0;
}

输入

代码语言:javascript
运行
复制
Enter a word / sentence (lowercaps) for encrypting : malware
Enter the key that you desire (eg. 14) : 2

输出

代码语言:javascript
运行
复制
Encrypted text : ocnyctg
票数 0
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32753441

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档