I'm here to trying to take input from the file. If user run this .exe
from cmd and give a filename like example.exe input.txt
then it shows the file and read. But if user doesn't give the file name then it run as simply program's run.
Program is running well when I give the input from cmd during run time it run perfectly, but if I don't give the filename during running this file and run simply example.exe
an exception show me the error
exception: invalid null pointer
my code is here:
// inputfile.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include<iostream>
#include<conio.h>
#include<string>
#include<fstream>
using namespace std;
void main(int argc, char* argv[])
{
try {
if (argc > 0)
{
string filename = argv[1];
ifstream in(filename);
in.open(filename);
if (in.is_open())
{
cout << "file opened, do something with file";
}
else
{
cout << endl << "You have Entered Wrong File Name Or File Not Exist in Project's Library" << endl;
}
}
}
catch (exception e)
{
}
cout << endl << "do with the simple program";
_getch();
}
The logic error is in the line
if (argc > 0)
It needs to be
if (argc > 1)
argv[1]
is NULL
if the program is invoked without arguments.
argc
is at least 1, the first argument being the name of the program. When the program is invoked with one argument, argc
is 2 and argv[1]
is the first argument.
When there is only one argument(always the exec file itself, eg using in the way ./exec_file or just double click the exec file), the argv[1] would throw an exception.
Here are some tips:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.