c - 使用命令行参数中的 getchar 和 putchar 来编码程序以发送到解码

标签 c command-line-arguments getchar putchar

所以我正在尝试制作一个编码/解码程序。到目前为止我还停留在编码部分。我必须能够从命令行参数获取消息,并使用种子随机数对其进行编码。该数字将由用户作为第一个参数给出。

我的想法是从 getchar 获取 int 并将随机数结果添加到其中。然后我想将其返回到标准输出,以便另一个程序可以将其读取为参数,以使用相同的种子对其进行解码。到目前为止,我无法让 putchar 正常工作。关于我应该解决或关注的问题有什么想法吗?提前致谢!

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

int main(int argc, char *argv[]) { 
    int pin, charin, charout;
    // this verifies that a key was given at for the first argument
    if (atoi(argv[1]) == 0) {
        printf("ERROR, no key was found..");
        return 0;
    } else {
        pin = atoi(argv[1]) % 27; // atoi(argv[1])-> this part should seed the srand
    }    

    while ((getchar()) != EOF) {        
        charin = getchar();        
        charout = charin + pin;        
        putchar(charout);        
    }    
}

最佳答案

您不应该调用 getchar() 两次,它会消耗流中的字符并且您会丢失它们,请尝试这样

while ((charin = getchar()) != EOF) {
    charout = charin + pin;
    putchar(charout);
}

此外,不要检查 atoi() 是否返回 0(这是一个数字和有效种子),而是执行此操作

char *endptr;
int pin;
if (argc < 2) {
    fprintf(stderr, "Wrong number of parameters passed\n");
    return -1;
}
/* strtol() is declared in stdlib.h, and you already need to include it */
pin = strtol(argv[1], &endptr, 10);
if (*endptr != '\0') {
    fprintf(stderr, "You must pass an integral value\n");
    return -1;
}

关于c - 使用命令行参数中的 getchar 和 putchar 来编码程序以发送到解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33427784/

相关文章:

无法弄清楚为什么 getchar() 在 C 中第一次出现时选择换行符

c - 将文本中的空格限制为只有一个 - c

c - 仅使用 getchar() 从输入中获取整数并转换为 int

c - 为什么 ftell( stdin ) 导致非法查找错误

c - 使用 scanf 输入数字后遇到严重错误

c++ - 可选的命令行参数

python - 将 sys.argv 合并到 python 中的 mySQL 查询中

c - 使用 execvp 时输入重定向问题?

c - WinAPI中如何让两个线程共享一个全局变量?

python - 在python中获取参数并维护argparse解析器的状态