Search code examples
ccommand-line-argumentsgetcharputchar

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.

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

Solution

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