参数检查

Dan*_*676 2 c++ error-handling arguments file

#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; 
    }
}
Run Code Online (Sandbox Code Playgroud)

除了一个问题,我已经让这个程序正常工作了

如果用户只运行没有文件名的程序(我认为被称为参数),例如./displayfile,那么我得到一个Segmentation错误

我如何修改我的代码,以便程序退出时出现"添加文件名"的错误消息

我的第一个想法就是这样

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

补充:以防万一使用g ++ displayfile.cpp -o displayfile进行编译

Cyc*_*ode 5

#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; 
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 顺便说一句,很好的解释。;-) (2认同)