C++怎么使用命令行参数读取文件,即文件应该放在哪?在主函数中怎么传入路径?下面是我写的一个测试程序,

我把文件与cpp文件放在了一起,不能执行,求高手解答!!!!
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main(int argc , char *argv[])
{
ifstream file1,file2;
file1.open(argv[1]);
string s;
while(!file1.eof())
file1>>s;
cout<<s<<endl;
file1.close();
file2.open(argv[2]);
while(!file1.eof())
file2>>s;
file2.close();
cout<<s<<endl;
system("pause");
return 0;

}

我调试过了 只有一处错误

使用方法 这个文件编译后的exe 假设叫 test.exe

那么 如果要读 1.txt 和 2.txt 那么 先要进入CMD(在运行里输入CMD回车)

不是你常用的控制台 虽然也是黑窗口

转到 test.exe所在目录 输入 test.exe 1.txt 2.txt 回车 就可以运行了 如果有路径 那么输入路径

有什么问题继续问 不行了远程协助

D:\Backup\我的文档\MyProjects\XLCS\20111217\Debug>20111217 1.txt 2.txt
1.txt内容
2.txt内容
请按任意键继续. . .

#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main(int argc , char *argv[])
{
ifstream file1,file2;
file1.open(argv[1]);
string s;
while(!file1.eof())
file1>>s;
cout<<s<<endl;
file1.close();

file2.open(argv[2]);
while(!file2.eof()) //这里的 file2 手误成file1了
file2>>s;
file2.close();
cout<<s<<endl;
system("pause");
return 0;
}追问

什么意思,我不是很懂,我编译后并没有可执行的exe文件,而且从file1.open(argv[1]);
就开始出错

追答

这种从main函数传参数的不能在VC6下运行

只能在VC6下连接 编译

编译好了用我上面说的方法运行

追问

我们还是qq上说吧
我135429617

追答

1227812201

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-12-17
int main(int argc , char *argv[]这个函数是要调用才能运行的, argc是指函数的输入参数的个数, argv指向字符串指针的指针,这是实际的输入参数的指针, 你可以自己百度一下windows下使用DOS环境调用函数,很简单的。
第2个回答  2011-12-17
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
int main(int argc , char *argv[])
{
ifstream file1,file2;
file1.open(argv[0],ios::out);//这里改改
string s;
while(!file1.eof())
file1>>s;
cout<<s<<endl;
file1.close();
file2.open(argv[1],ios::out);//这里改改

while(!file1.eof())
file2>>s;
file2.close();
cout<<s<<endl;
system("pause");
return 0;

}追问

不行,一样是错误的,再说不应该从argv[1]开始读吗?

第3个回答  2011-12-17
mian()函数是不能被其他函数调用的,但是 计算机的 操作系统 可以调用主函数。
具体方法:把源程序编译并链接后的可执行文件和要合并的CPP文件复制到D盘->将可执行文件重命名为mycomm.exe->打开命令提示符窗口->输入d:回车->然后输入 mycomm file1.cpp file2.cpp 回车->完毕 如果你的程序逻辑没错误 应该是能达到预期功能
相似回答