Redirect from file to stdin

Re: Redirect from file to stdin

von Richard Lobb -
Anzahl Antworten: 0
Firstly, are you sure you need to read the numbers from a file? I just created a Python3 CodeRunner question where the answer is a program to read numbers from stdin until EOF and then to print the count of numbers read and their average. I generated a test file of 10^6 random floats, one per line, and pasted the entire 8 MB file into the Test Case Standard Input field. It took several seconds to process the paste and then to save the question, but it ran just fine. All one million numbers were read and processed. The entire stdin contents aren't displayed in the result table, as CodeRunner snips out the middle of very long strings anywhere in the result table. If you wish to hide the standard input column altogether you can do so by turning on Customise and editing the Result Column field.

If you do wish to redirect stdin to a text file supplied as a support file, it's easy in Python, harder in C++.

In Python you can customise the question, turn off the Is Combinator checkbox and replace the template with a much simpler version (because it runs a job for each test case separately) that inserts before the student answer a couple of lines of code to redirect stdin as shown in the following image. The name of the datafile for the testcase must be inserted in the testcase Extra field.

The customised template and Combinator checkbox setting.

This approach allows every test case for the question to read from a different file.

There is no such easy option in C++ however. You have two options:
  1. If you can get by with just a single testcase for the question you can customise it and set up the Sandbox parameters field to include a runargs parameter (denoting "run arguments") like the following (where nums.txt has been added to the question as a support file):

    Showing runargs
  2. If you want something like the Python solution, with a different file for each test case, you will need to take complete control of the compile-and-execute process by scripting it in Python as explained in the documentation here. That example shows the general approach for C; you would need to change it for C++ and include an extra parameter in the subprocess.check_output call to set up stdin to the file nominated by the Extra field of the testcase. I doubt it's worth the effort but postback if you need more details.