Home > other >  How do I take a set of user input numbers when there are no command line args in C? ISO C17 WIndows
How do I take a set of user input numbers when there are no command line args in C? ISO C17 WIndows

Time:02-23

I'll preface this with the standard: I am very new to C programming so please be gentle.

I'm writing a C program that should be able to take a file path/filename as a command line arg, failing that, it should accept user input. I have the argv[1] filename working, but I don't know how to get it to switch to stdin if the user doesn't add a file name as an arg. The input should be raw data, not a filename. here's my (very newbie) code. As a new programmer I may need some extrapolation of explanation and I apologize in advance for this.

int main(int argc, char* argv[]) {
    
    #ifndef NDEBUG
        printf("DBG: argc = %d\n", argc);
        for (int i = 1; i < argc;   i)
            printf("DBG: argv[%d] = \"%s\"\n", i, argv[i]);
    #endif

    FILE* stream = fopen(argv[1], "r");
    
    char ch = 0;
    size_t cline = 0;
    
    char filename[MAX_FILE_NAME];
    filename[MAX_FILE_NAME - 1] = 0;
    
    
    if (argc == 2) {
        stream = fopen(argv[1], "r");
        if (stream == NULL) {
            printf("error, <%s> ", argv[1]);
            perror(" ");
            return EXIT_FAILURE;
        }
    }
    else if (argc ==1)
    
        printf("Enter a list of whitespace-separated real numbers terminated by EOF or \'end\'\n");
    
    //continue with program using user-input numbers 

CodePudding user response:

Your code is overly complicated and wrong. You're doing things in the wrong order. You first need to check if an argument is there and try to open the file only in that case.

You want something like this:

#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>

int main(int argc, char* argv[]) {

  FILE* input = stdin;   // stdin is standard input
                         // so if no arguments are given we simply read
                         // from standard input (which is normally your keyboard)

  if (argc == 2) {
    input = fopen(argv[1], "r");
    if (input == NULL) {
      fprintf(stderr, "error, <%s> ", argv[1]);
      perror(" ");
      return EXIT_FAILURE;
    }
  }
  else
    printf("Enter a list of whitespace-separated real numbers terminated by EOF or \'end\'\n");

  double number;
  while (fscanf(input, "%lf", &number) == 1)
  {
    // do whatever needs to be done with number
    printf("number = %f\n", number);
  }

  fclose(input);
}
  •  Tags:  
  • c
  • Related