使用命令行参数中的getchar和putchar编码程序以发送以进行解码 [英] encode program using getchar from command line argument and putchar to send to decode
问题描述
所以我正在尝试制作一个编码/解码程序。到目前为止,我还停留在编码部分。我必须能够从命令行参数中获取一条消息,并使用种子随机数对其进行编码。该数字将由用户作为第一个参数给出。
So I'm trying to make a encode/decode program. So far I'm stuck in the encode part. I have to be able to get a message from the command line arguments, and encode it using a seeded random number. This number will be given by the user as the first argument.
我的想法是从getchar中获取整数,然后向其中添加随机数结果。然后,我想将其返回到std,以便另一个程序可以将其读取为参数,以使用相同的种子对其进行解码。到目前为止,我无法正常使用Putchar。对我应该解决或关注的问题有任何想法吗?提前致谢!
My idea is to get the int from getchar and just add random number result to it. I then want to get it back to the std out so that another program can read it as an argument to decode it using the same seed. So far, I can't get the putchar to work properly. Any ideas on what I should fix or focus in? Thanks in advance!
#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()
,它会消耗流中的字符,而您会丢失它们,请尝试这样
You should not call getchar()
twice, it consumes the characters in the stream and you lose them, try like this
while ((charin = getchar()) != EOF) {
charout = charin + pin;
putchar(charout);
}
此外,也不要检查 atoi()
返回 0
这是一个数字和有效的种子,执行此操作
Also, instead of checking if atoi()
returns 0
which is a number and a valid seed, do this
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;
}
这篇关于使用命令行参数中的getchar和putchar编码程序以发送以进行解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!