【问题标题】:encode program using getchar from command line argument and putchar to send to decode使用命令行参数中的 getchar 和 putchar 对程序进行编码以发送到解码
【发布时间】:2015-10-30 02:35:16
【问题描述】:

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

我的想法是从 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);        
    }    
}

【问题讨论】:

  • 使用strtol() 确保int 已通过,并检查argc 的值。

标签: c command-line-arguments getchar putchar


【解决方案1】:

你不应该调用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;
}

【讨论】:

  • 它正在工作。很棒的提示!我仍然缺少一些东西。该消息不是从命令行参数中读取的,而是在程序开始运行并且我键入它之后。关于如何让它直接从命令行读取参数的任何想法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-11
  • 2021-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多