Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument checking

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main (int argc, char* argv[])
{
    string STRING;
    ifstream infile;    
    STRING = argv[1];
    infile.open(argv[1]);   
    if (infile.fail())// covers a miss spelling of a fail name
    {
        cout << "ERROR. Did you make a mistake in the Spelling of the File\n";
        return 1;
    }
    else
    {
        while(!infile.eof())
        {
            getline(infile,STRING); // Get the line
            cout<<STRING + "\n"; // Prints out File line
        }   
        infile.close(); 
        return 0; 
    }
}

I have got this program working fine apart from one problem

if the user only runs the program with no file name (what I believe to be called arguments) e.g ./displayfile then I get a Segmentation fault

How would I amend my code so that the program would exit with an error message along the lines of "Add a file name"

My first thought is something along the lines of

if (!argc=2)
{
    cout << "ERROR. Enter a file name";
    return 1;
}

ADDED: just in case this matters am compiling using g++ displayfile.cpp -o displayfile

like image 257
Dan1676 Avatar asked Feb 10 '26 08:02

Dan1676


1 Answers

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main (int argc, char* argv[]) {
   if(argc != 2) {
      cout << "You need to supply one argument to this program.";
      return -1;
   }

   string STRING;
   ifstream infile;    
   STRING = argv[1];
   infile.open(argv[1]);   
   if (infile.fail())// covers a miss spelling of a fail name {
      cout << "ERROR. Did you make a mistake in the Spelling of the File\n";
      return 1;
   }
   else {
      while(!infile.eof()) {
         getline(infile,STRING); // Get the line
         cout<<STRING + "\n"; // Prints out File line
      }   
      infile.close(); 
      return 0; 
   }
}
like image 61
Cyclonecode Avatar answered Feb 12 '26 21:02

Cyclonecode