encode program using getchar from command line argument and putchar to send to decode

痞子三分冷 提交于 2019-12-12 18:21:58

问题


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.

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);        
    }    
}

回答1:


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);
}

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


来源:https://stackoverflow.com/questions/33427784/encode-program-using-getchar-from-command-line-argument-and-putchar-to-send-to-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!