[英]input file from command line
我在这里尝试从文件中获取输入。 如果用户从cmd运行此.exe
并提供诸如example.exe input.txt
类的文件名,则它将显示该文件并读取。 但是,如果用户不提供文件名,那么它将像程序的运行一样运行。
当我在运行时从cmd提供输入时,程序运行良好,它运行得很好,但是如果我在运行此文件时不提供文件名而仅运行example.exe
,则异常会向我显示错误
异常:无效的空指针
我的代码在这里:
// 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();
}
逻辑错误在行
if (argc > 0)
它必须是
if (argc > 1)
如果在不带参数的情况下调用程序,则argv[1]
为NULL
。
argc
至少为1,第一个参数是程序的名称。 当使用一个参数调用程序时, argc
为2,而argv[1]
为第一个参数。
当只有一个参数时(始终是exec文件本身,例如,使用./exec_file或双击exec文件),argv [1]将引发异常。
这里有一些提示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.