I'm trying to figure out how to be able to read in a .txt file as a command prompt argument instead user input. If I have the program
#include <iostream>
#include "cmdline.h"
using namespace std;
int main (int cnt, char * args[]) {
int a = cmdline_int(args, 1);
int b = cmdline_int(args, 2);
cout << "sum = " << a << " + " << b << " = " << a + b << endl;
return 0;
}
where the file "cmdline.h" contains
#include <cstdlib>
#include <string>
using namespace std;
int cmdline_int( char* cmdline_a[], int n ) {
return atoi( cmdline_a[ n ] );
}
char cmdline_char( char* cmdline_a[], int n ) {
char c = cmdline_a[ n ][0];
return c;
}
I can run the program as
./program 3 5
and the output will be
sum = 3 + 5 = 8
however if I have a file (textfile.txt) that simply contains those same numbers in list form, i.e.
3
5
and try to run it as
./program < textfile.txt
I get
Segmentation fault
it does the same thing if textfile.txt contains "3 5", though its important that I use a text file in list form anyway. What do I need to change to make "./program textfile.txt" have the same output as "./program 3 5" ?
I'm guessing the problem lies between the int main parenthesis, I'm just not sure what specifically.