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