0

Writing C code on visual studio 2017, I want to set the argument automatically from txt file instead of typing it myself.

Chance my project's properties on debug-command arguments wouldn't work - maybe I've done it wrong.

scanf ("%d",&N,&T,&F,&L); 

is an example for a line in code I wish to scan those variables from a txt file already made and so on many other lines.

  • 1
    Have you considered redirecting the input from a prepared file? For example `myprog < input.txt` in a console. – Weather Vane May 14 '19 at 21:11
  • @WeatherVane I guess the OP is pressing F5 in Visual Studio. Can you redirect the input in the project settings? – Peter - Reinstate Monica May 14 '19 at 22:13
  • @PeterA.Schneider you read the question more carefully then I did. Perhaps [like this](https://stackoverflow.com/questions/14043986/debugging-with-visual-studio-using-redirected-standard-input). – Weather Vane May 14 '19 at 22:17
  • The setting is explained [here](http://cs-people.bu.edu/deht/CS585/VSTutorial/#CommandLineArgs). Command line arguments appear in the parameter `argv`: `argv[0]` is the program name, `argv[1]` contains a char pointer to the first command line argument, if any, else 0, `argv[2]` points to the second one etc. You need to `fopen()` the file, e.g. with `fopen(argv[1], "r")`. It's best to use absolute path names like `C:\temp\data.txt` in order to avoid confusion about the current directory. `fopen()` returns a `FILE` pointer which is then used as the first parameter to `fscanf()`. – Peter - Reinstate Monica May 14 '19 at 22:19
  • Actually @WeatherVane's suggestion is good because it is more versatile. Redirect the input (the program will think somebody is typing it in, but the operating system feeds the text from the given file) and simply use `scanf()` in your program. That way you can read from a file or the console without changing the program (but you must change the project settings respectively type a different command in the console). – Peter - Reinstate Monica May 14 '19 at 22:26

1 Answers1

0

You need the fopen() function which will open a pointer to your text file. See this tutorial on fopen(). If you want to change the file names everytime you run the program, you can pass the filename as an argument to your program. See this tutorial on using arguments in C++/C.

ias
  • 314
  • 2
  • 14
  • Consider elaborating on your answer, rather than rely on details from a link. –  May 14 '19 at 22:10