ccommand-line-interfacegetchar

getchar to read from command line arguments


I want to get my program to use the command line arguments with getchar to then encode a message. My problem is that getchar is only paying attention to what I type after the program has executed. How can I make it read the command line arguments instead?

#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 {
        srand(atoi(argv[1]));
        pin = rand() % 27;
    }
    while( (charin=getchar()) != EOF){
        charout = charin + pin;
        putchar(charout);
    }
}

Solution

  • getchar to read from command line arguments

    That's the problem - if you are getting command line arguments you don't do it with getchar: use argc to get the count of arguments and argv[] to get particular arguments.

    I don't think you need getchar in this program at all.

    These are also good suggestions, please take a look at the parts about argument handling:

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

    I think you are trying to write a program that behaves like this:

    program pin message

    and then it will use some sort of Caesar cipher on message to obfuscate the output. Is that right?

    If so, then you need to also get argv[2] and use printf to output the results.