The code I was looking at was here
Command Line Arguments in C++ - Cprogramming.com
(copied and pasted to the bottom of this post for your viewing pleasure)
I pretty much wrote it out just replacing agrv[1] with a file i created (creatively called file.txt)
however, I couldn't get it to work. i told it to print out argc and it outputted 1, rather than 2.
when i changed the first if to give it the logic to continue as though argc was ==1 eg
it then works fine.
i don't get why since tutorial this tells me it should be 2!
any help much appreciated.
tyia
Code:
#include <fstream>
#include <iostream>
using namespace std;
int main ( int argc, char *argv[] )
{
if ( argc != 2 ) // argc should be 2 for correct execution
// We print argv[0] assuming it is the program name
cout<<"usage: "<< argv[0] <<" <filename>\n";
else {
// We assume argv[1] is a filename to open
ifstream the_file ( argv[1] );
// Always check to see if file opening succeeded
if ( !the_file.is_open() )
cout<<"Could not open file\n";
else {
char x;
// the_file.get ( x ) returns false if the end of the file
// is reached or an error occurs
while ( the_file.get ( x ) )
cout<< x;
}
// the_file is closed implicitly here
}
}