C++ 找不到命令行参数(文件)

C++ command line args (file) not found?

本文关键字:文件 参数 找不到 命令行 C++      更新时间:2023-10-16

>我有以下主要方法:

int main(string argf)
{
ifstream exprFile(argf);
string inExpr;
if (exprFile.is_open())
{
while ( getline(exprFile,inExpr) )
{
    //do stuff
}
exprFile.close();
}
else cout << "Unable to open file"; 
system("pause"); // to wait for user input; allows the user to see what was printed before the window closes
return 0;
}

我使用以下方法从命令行运行此程序:

  • "C:\Complete Filepath\Project2.exe" "C:\Differnt Filepath\args.txt"
  • C:\Complete Filepath\Project2.exe C:\Differnt Filepath\args.txt
  • "C:\Complete Filepath\Project2.exe" "args.txt"
  • C:\Complete Filepath\Project2.exe args.txt

最后两个带有 args .txt与可执行文件位于同一目录中。所有四个都给出了"无法打开文件"结果。试图在对argf值执行任何操作之前打印它没有任何结果。完全空白的打印语句。

然后,我进入Visual Studio 2010选项,并在参数部分下添加了args.txt文件的所有变体,该文件也位于不同的位置,没有任何效果。

我做错了什么?

您应该如何打开在命令行上作为参数传递的文件?

int main ( int argc, char *argv[] )

这是从main那里获得论据的正确方法。

argc是参数的数量。 argv是参数列表。

实际参数将以index = 1.值开头index 0值将始终是程序名称。

在您的示例中,

"C:\Complete Filepath\Project2.exe" "C:\Differnt Filepath\args.txt"

argc = 2
argv[0] = "Project2.exe" 
argv[1] = "C:Differnt Filepathargs.txt"

耶,代码!

#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char* argv[])
{
   ifstream exprFile;
   string inExpr;
   for( int i = 1; i < argc; i++) {  // 0 is the program name
      exprFile.open(argv[i]);
      if (exprFile.is_open()) {
         while ( getline(exprFile,inExpr) ) {
            cout << "Doing stuff on line: " << inExpr << "n";
         }
         exprFile.close();
      }
      else cout << "Unable to open file " << argv[i];
   }
}