【问题标题】:adding repetition to calling a function添加重复调用函数
【发布时间】:2015-12-13 04:19:36
【问题描述】:

好的,我正在尝试编写一个代码,将输入的字符串中的字符替换为字母表中的下一个字符,并打印 26 次(所有字母都旋转)
我从 rot13 代码中获得了帮助,对其进行了一些修改,除了打印 26 次之外,它做了我想要的一切。我试图用 for 和 while 添加一个计数器,但我真的看起来很愚蠢,当然没有工作。

这是代码

#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("Please Enter The Secret Code\n");
    int code;
    while((code = getchar())) {
        code = chariot(code);
        putchar(code);
    } 
    return 0;
}

int chariot(int code)
{
    if('a' <= code && code <= 'z'){
        return Chariot(code,'a');
    } else if ('A' <= code && code <= 'Z') {
       return Chariot(code, 'A');
    } else {
        return code;
    }
}

int Chariot(int code, int newcode){
    code = (((code-newcode)+1)%26)+newcode;
    return code;
}

【问题讨论】:

  • 不确定我理解你想要什么,但如果你的意思是 read in "cat" 然后打印 "dbu", "ecv" ..... "bzs" ,你应该改变首先读取整个字符串的代码,然后才在循环中对其所有字符运行 Chariot 函数 26 次,每次调用后打印结果。
  • 您的输入是什么,您期望什么输出?给我们一些样品。
  • @ShvetChakra 我希望它像这样 aAzZ->bBaA->cCbB.......->zZaA 现在我在函数中添加了循环并使其正常工作,但我无法做到每一步都打印代码它只打印最后一步

标签: c string function repeat


【解决方案1】:

你需要做的是运行最后一点:

int Chariot(int code, int new code)
{
    code = (((code-newcode)+1)%26)+newcode;
    return code;
}

通过“for”循环。

它应该是这样的:

int Chariot(int code, int new code)
{

    for (int i = 0; i < 26; i++)
    {
        code = (((code-newcode)+1)%26)+newcode;
    }
    return code;
}

这样做的目的是将同一段代码运行 26 次,这就是您想要的结果。对循环进行更多研究,因为它们会极大地帮助您的生活。

【讨论】:

  • 感谢这位成功的人,现在它可以工作 26 次,但还有 1 个问题。它没有任何区别,因为它不会打印出每一步输出仍然相同,但无论如何谢谢,如果可以的话,我会投票
  • 如果你想让它打印出每一步,你所要做的就是在 for 循环内打印,它会打印 26 次。尝试使用像这样的 sn-p: for (int i = 0; i
  • 试过了,但现在当我运行并输入字符串时它停止工作我认为这可能是因为我没有使用 scanf 获取字符串,但我使用 getchar 进行了
【解决方案2】:

如果你坚持逐个字符处理输入,你可以在足够高的VT100兼容终端上使用这个:

    while (code = getchar())
    {
        int i;
        for (i = 0; i < 26; ++i)
            if (putchar(code = chariot(code)) != '\n') printf("\b\v");
        if (code != '\n') printf(" \e[26A");
    }

当然,这很荒谬。理智的解决方案是 o_weisman 建议的:

首先读取整个字符串,然后才运行 Chariot 函数 循环中的所有字符 26 次,每次打印结果 打电话。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    相关资源
    最近更新 更多