参数检查
#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;
}
}
我已将此代码添加到我的程序中,但我仍然遇到分段错误 – Dan1676
好的解释方式。 ;-) – netcoder
嗯,我们总是可以使用这样的东西:你犯了一个错误,因此我不会执行=) – Cyclonecode
除了为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
试图读取文件末尾时才设置,所以您实际上会打印一个(可能是空的)行太多。只需检查getline
的返回值即可找到任何错误或文件结尾。
输出时不要将换行符添加到字符串上,只是在字符串之后放出。最后但并非最不重要的一点,不需要infile.close
,因为无论如何析构函数都会调用它。
检查'argc',(“c”为count)不是argv。 – Mat
你的意思是argc,而不是argv? – 2011-11-18 13:16:44
好的,通常的做法是至少检查'argc'的值。 – jv42