简体   繁体   English

从命令行输入文件

[英]input file from command line

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. 如果用户从cmd运行此.exe并提供诸如example.exe input.txt类的文件名,则它将显示该文件并读取。 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 当我在运行时从cmd提供输入时,程序运行良好,它运行得很好,但是如果我在运行此文件时不提供文件名而仅运行example.exe ,则异常会向我显示错误

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. 如果在不带参数的情况下调用程序,则argv[1]NULL

argc is at least 1, the first argument being the name of the program. argc至少为1,第一个参数是程序的名称。 When the program is invoked with one argument, argc is 2 and argv[1] is the first argument. 当使用一个参数调用程序时, argc为2,而argv[1]为第一个参数。

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. 当只有一个参数时(始终是exec文件本身,例如,使用./exec_file或双击exec文件),argv [1]将引发异常。

Here are some tips: 这里有一些提示:

  1. Try to learn how to debug the code(IDE like Visual Studio, Ecplise or gdb). 尝试学习如何调试代码(如Visual Studio,Ecplise或gdb等IDE)。
  2. VC++ is not standard c++, which means it only runs on Windows, not cross-platform. VC ++不是标准的c ++,这意味着它只能在Windows上运行,不能在跨平台上运行。 You'd better learn to use g++ compiler(linux). 您最好学会使用g ++编译器(Linux)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM