使用getchar从命令行参数编码程序,并使用putchar发送到解码

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

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

#include  #include  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; }