I am being asked to use command line arguments and read from files for the first time. I wrote the code the best I know how to calculate a least squares linear regression line. I think it is correct but now I have to change it so that instead of prompting the user for input, the program takes a single command line argument containing the name of a file. The file then contains two doubles on each line, separated by a space, with the first representing an x value and the second representing a y value. I need to use these values to form my vectors of x and y observations. The program should report all of the same
analysis as the original program.
I am really lost about where to start with making the changes. Do I need to change things outside of the main function? I know I need to add the following to the main statement but after that I am confused.
int main(int argc, char* argv[])
{
if argc != 2)
{
// show error msg - like usage program.exe filename
return 1;
}
// filename in argv[i]
ifstream(argv[1]);
// check if stream is valid and load data if it is or sgow error msg
}
Do I need to change things outside of the main function? I know I need to add the following to the main statement but after that I am confused.
int main(int argc, char* argv[]){***}
Only main() will need to be changed, the rest of the code remains as it is.
Start by familiarising yourself with the command-line arguments. Sample program
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
usingnamespace std;
int main(int argc, char * argv[])
{
for (int i=0; i<argc; ++i)
{
cout << i << " " << argv[i] << '\n';
}
}
If you compile and run that, it should output a line starting with 0 and then the path/name of the program itself. If you run the program from the command line, you can type whatever arguments you like after the program name.
Assume your program is named test.exe, and you type
test.exe hello world
Then the output should be something like this:
0 test.exe
1 hello
2 world
In order to use it to get the file name, the program might look like this: