#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显示文件
最佳答案
#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;
}
}