C++ 找不到命令行参数(文件)
C++ command line args (file) not found?
>我有以下主要方法:
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];
}
}
相关文章:
- 在 cpp 文件中隐藏采用模板参数引用的方法
- 读取大文件(>2GB)(文本文件包含以太网数据)并通过不同参数随机访问数据的最佳方法是什么?
- 是否可以在命令行中将输入参数传递给可执行文件
- 如何使用输入参数作为文件的传递?
- 隐蔽的 gcc 参数到 CMake 文件
- 生成文件文件名参数
- 在实现文件中使用模板参数声明方法
- 提供变量作为 MATLAB 系统命令的输入参数,以便C++可执行文件
- 如何在 c++ 窗口中将参数和返回的退出值传递到批处理文件/从批处理文件获取返回的退出值
- 编写一个将 LLVM IR 文件作为命令行参数的程序
- 通过命令行参数获取llvm ir文件时面临问题
- 如何使输入文本文件成为构造函数参数?c++
- (C/C++)fscanf_s从txt文件以字符形式读取数组时缺少整数参数错误
- 如何在不使用文件扩展名的情况下使用命令行参数打开C++中的文本文件?
- 读取用户必须提供一些参数的文件
- 如何使用 QProcess 设置参数以运行类文件?
- 可变参数模板在目标文件中有重复的符号?
- C++输入重定向导致文件参数工作时出错
- g++ 对象文件参数位置很重要,并给出无法正常编译的不同结果
- c++使用GetPrivateProfileString读取配置文件参数