-1

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);
    }
}
SergA
  • 1,097
  • 13
  • 21
  • I dont get it, the program recieves its argument via argv, you have them there, what is it that you are trying to read? – JSelser Oct 30 '15 at 04:33
  • you are reading correctly your command line input, what do you want to do ? – HDJEMAI Oct 30 '15 at 04:42
  • 1
    have you specified the commandline arguments? simply running the code from an IDE would not do that. also **My problem is that getchar is only paying attention to what I type after the program has executed.**, what does that even mean? – Swastik Padhi Oct 30 '15 at 05:01
  • This question is somewhat confusing but I'm guessing you want to compare a randomly generated data with one from program arguments. Make use of strcmp to check strings and sprintf to make a string from an integer. – Mike -- No longer here Oct 30 '15 at 06:01
  • in general, do not ever use a argv[] value greater than `argv[0]` until have examining `argc` to assure the desired argument exists. BTW: when the desired command line argument does not exist, output a 'usage' message to let the user know what went wrong. – user3629249 Oct 31 '15 at 13:22
  • this line: `charout = charin + pin;` will not `wrap` around the printable characters, so some characters, like 'z' for example, will be trying to output unprintable values (assuming ASCII) – user3629249 Oct 31 '15 at 13:28

1 Answers1

2

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.

Community
  • 1
  • 1
davejagoda
  • 2,420
  • 1
  • 20
  • 27