简体   繁体   English

从命令提示符运行程序并在 C++ 中使用 argv

[英]Running a program from command prompt and using argv in C++

I have written a program that takes the filename from argv[1] and do operations on it.我编写了一个程序,它从 argv[1] 获取文件名并对其进行操作。 When debugging from visual studio I pass the filename from project options>>debugging>>command arguments and It works fine and prints all results correctly.从 Visual Studio 调试时,我从项目选项>>调试>>命令 arguments 传递文件名,它工作正常并正确打印所有结果。

But when trying from the command prompt, I go to the dir of project/debug the I type但是当从命令提示符尝试时,我 go 到项目目录/调试我输入

program

It works fine and prints "No valid input file" in the same window (Which is my error handling technique)它工作正常并在同一个 window 中打印“没有有效的输入文件” (这是我的错误处理技术)

but when i type但是当我输入

program test.txt

It just does nothing.它什么也不做。 I think no problem in code because it works fine from the debugger.我认为代码没有问题,因为它在调试器中运行良好。

Code:代码:

int main(int argc, char *argv[]) 
 { 
int nLines;
string str;

if(argv[1]==NULL)
{
    std::cout << "Not valid input file" << endl;
    return 0 ;

}
ifstream infile(argv[1]);

getline(infile,str);
nLines = atoi(str.c_str());//get number of lines

for(int line=0 ;line < nLines;line++)
{
    //int currTime , and a lot of variables ..
            //do a lot of stuff and while loops
          cout << currTime <<endl ;

}
    return 0 ;
    }

You don't check if file was successfully opened, whether getline returned error code or not, or if string to integer conversion didn't fail.您不检查文件是否已成功打开,getline 是否返回错误代码,或者字符串到 integer 的转换是否失败。 If any of those error occur, which I guess is the case, nLines will be equal to 0 , no cycles will be performed and program will exit with return code 0 .如果发生任何这些错误,我猜是这种情况, nLines将等于0 ,不会执行任何循环,程序将退出并返回代码0

This code worked correctly for me running on the command line.这段代码对我在命令行上运行正常。

#include <string>
#include <algorithm>
#include <functional>
#include <vector>
#include <iostream>
using namespace std;

int main(int argc, char *argv[]) 
{ 
    int nLines;
    string str;

    if(argv[1]==NULL)
    {
        std::cout << "Not valid input file" << endl;
        return 0 ;

    }
    else
        std::cout << "Input file = " << argv[1] << endl;
}

Output: Output:

C:\Users\john.dibling\Documents\Visual Studio 2008\Projects\hacks_vc9\x64\Debug>hacks_vc9.exe hello
Input file = hello

By the way, this code is dangerous, at best:顺便说一句,这段代码是危险的,充其量是:

if(argv[1]==NULL)

You should probably be checking the value of argc before attempting to dereference a possibly-wild pointer.在尝试取消引用可能是野生指针之前,您可能应该检查argc的值。

The file probably contains an invalid numeric first line (perhaps starting with a space or the BOM ).该文件可能包含无效的数字第一行(可能以空格或BOM开头)。

That would explain no output, since if nLines == 0 no output should be expected这可以解释没有 output,因为如果nLines == 0则应该没有 output

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

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