[英]Argument checking
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (int argc, char* argv[])
{
string STRING;
ifstream infile;
STRING = argv[1];
infile.open(argv[1]);
if (infile.fail())// covers a miss spelling of a fail name
{
cout << "ERROR. Did you make a mistake in the Spelling of the File\n";
return 1;
}
else
{
while(!infile.eof())
{
getline(infile,STRING); // Get the line
cout<<STRING + "\n"; // Prints out File line
}
infile.close();
return 0;
}
}
除了一个问题,我的程序运行正常
如果用户只运行没有文件名的程序(我认为这是自变量),例如./displayfile,那么我会遇到细分错误
我将如何修改我的代码,以使程序将退出并显示一条错误消息,如“添加文件名”
我的第一个想法是
if (!argc=2)
{
cout << "ERROR. Enter a file name";
return 1;
}
添加:万一这很重要,请使用g ++ displayfile.cpp -o displayfile进行编译
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (int argc, char* argv[]) {
if(argc != 2) {
cout << "You need to supply one argument to this program.";
return -1;
}
string STRING;
ifstream infile;
STRING = argv[1];
infile.open(argv[1]);
if (infile.fail())// covers a miss spelling of a fail name {
cout << "ERROR. Did you make a mistake in the Spelling of the File\n";
return 1;
}
else {
while(!infile.eof()) {
getline(infile,STRING); // Get the line
cout<<STRING + "\n"; // Prints out File line
}
infile.close();
return 0;
}
}
除了对argc != 2
的明显检查之外,我不禁修复了一些较差的代码和明显的错误:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main (int argc, char* argv[])
{
if (argc != 2)
{
cout << "ERROR. Invalid number of arguments\n";
return 1;
}
ifstream infile(argv[1]);
if (!infile) // covers a miss spelling of a fail name
{
cout << "ERROR. Did you make a mistake in the Spelling of the File\n";
return 1;
}
string STRING;
while(getline(infile, STRING))
cout << STRING << '\n'; // Prints out file line
return 0;
}
您不需要调用ifstream::open
,只需使用构造函数,同样,您也不需要这么早声明STRING
,也不需要将其初始化为文件名,因为您无需使用它。 别忘了,这不是C语言,在每个函数的开头都不需要一团糟的声明。
其次,检查流的标志通常不是一个好主意,只需检查!infile
即可发现任何错误。 但是真正的错误是在while条件下检查infile.eof
,因为只有在getline
试图读取文件末尾时才会设置infile.eof
,所以实际上您会打印太多(可能是空的)行。 只需检查getline
的返回值即可发现任何错误或文件结尾。
并且不要在输出时在字符串上添加换行符,只需将其放在字符串后面即可。 最后但并非最不重要的一点是,不需要infile.close
,因为析构函数infile.close
调用它。
更改STRING = argv[1];
到if (argv[1] != null) STRING = argv[1];
虽然还不确定,所以您必须先对其进行测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.