【发布时间】:2017-01-27 02:37:42
【问题描述】:
课堂上的作业是测试提供的参数。编写的代码(添加到本主题)有效(在它运行的意义上),但它只产生第一个单词或一组单词。
代码:
#include <fstream>
#include <iostream>
using namespace std;
int main ( int argc , char *argv[] )
{
if(argc > 1 )
{
cout << argv[1] << endl;
}
else
{
return -1;
}
ifstream infile(argv[1]);
if (infile.is_open())
{
string words;
while (infile >> words)
{
cout << words <<endl;
}
}
else
{
return -1;
}
infile.close();
}
给定的行是:
"This is true" "This is fact"
它(代码)产生的结果是:
This is true
我想要的结果是:
This is true , this is fact
另一个例子:
给定的行:
check if this thing works
使用此代码输出:
check
想要的输出:
check, if, this, thing, works
我的问题是,如果我没有在代码中添加会产生整行的内容。另外,我知道我的代码没有在输出中添加“,”,但我想一次担心一个问题。
更多信息:
文件被读取,如果没有 arg,那么它不会产生任何东西,如果只有一个 arg,它也可以工作。他的代码在不止一个 arg 和引号处停止工作。
【问题讨论】:
-
我可能在这里遗漏了一些东西,但代码读取了一个名称由
argv[1]给出的文件。那么"This is true" "This is fact"应该如何产生This is true , this is fact?它将寻找并打开一个名为"This is true"的文件,文件内容未知! -
是的,您是要打印参数还是参数中指定的文件内容?
-
我希望您在当前文件夹中没有名为“这是真的”且没有扩展名的文件。
标签: c++ command-line-arguments