我正在尝试输入
的格式“ prog1 1所有文件1”
第一个输入必须为argv [1],应为整数。
因此,我需要一种方法来确定是否将argv [1]输入为字符串“ xxx”(“ prog1 xxx”),它应返回“ NO PHRASE LENGTH”,但返回“ INVALID PHRASE LENGTH”。
我看到有一个isdigit()函数,但是我不确定我将如何使用它。
int main(int argc, char *argv[]){
try{
if(argc == 1){
cout << "NO PHRASE LENGTH" << endl; exit(1);
}
else if((stoi(argv[1])) <= 0 ){
cout << "INVALID PHRASE LENGTH" << endl; exit(1);
}
else if(argc == 2){
cout << "NO MODE" << endl; exit(1);
}
else if(!(std::string(argv[2]) == "all") && !(std::string(argv[2]) == "top")){
cout << "INVALID MODE" << endl;
}
else if(argc == 3){
cout << "NO FILES GIVEN" << endl;
}
else if(argc >= 4){
ifstream f;
for(int i = 4; i < argc; i--){
f.open( argv[i] );
if( ! f.good() ) {
cout << "BAD FILE " << argv[i] << endl; exit(1);
}
//cout << "OK" << endl;
//f.close();
}
}
else
return 0;
}
catch(exception e){
}}
答案 0 :(得分:2)
您的代码非常混乱。我不确定您正在使用for循环来打开文件。无论如何,我已经举了一个例子。
int main(int argc, char *argv[])
{
if(argc != 4)
{
cout << "Program requires 3 parameters!" << endl;
return -1;
}
if(std::string(argv[2]) != "all" && std::string(argv[2]) != "top")
{
cout << "INVALID MODE" << endl;
return -1;
}
try
{
if(stoi(argv[1]) < 1)
{
cout << "ZERO OR NEGATIVE PHRASE LENGTH" << endl;
return -1;
}
ifstream f(argv[3]);
if(!f)
{
cout << "BAD FILE " << argv[3] << endl;
return -1;
}
// Now do whatever you want with the opened file
}
catch(out_of_range e)
{
cout << "NON-INT PHRASE LENGTH" << endl;
return -1;
}
return 0;
}
答案 1 :(得分:0)
当您只想说std::endl
(或'\n'
)时,不要使用"...\n"
。 std::endl
不仅在流中插入换行符,还刷新了它。如果您真的要冲洗流,请使用std::flush
。
如果还有其他方法,请不要使用exit()
结束程序。如果您使用exit()
,则不会发生堆栈展开。
#include <cstdlib>
#include <string>
#include <iostream>
#include <exception>
#include <fstream>
int main(int argc, char **argv)
{
if (argc == 1) {
std::cerr << "NO PHRASE LENGTH\n";
return EXIT_FAILURE;
}
if (argc == 2) {
std::cerr << "NO MODE\n";
return EXIT_FAILURE;
}
if (argc == 3) {
std::cerr << "NO FILES GIVEN\n";
return EXIT_FAILURE;
}
int phrase_length;
try {
phrase_length = std::stoi(argv[1]);
if (phrase_length < 0)
throw std::out_of_range{ nullptr };
}
catch (std::invalid_argument) {
std::cerr << "NO PHRASE LENGTH";
return EXIT_FAILURE;
}
catch (std::out_of_range) {
std::cerr << "PHRASE LENGTH OUT OF RANGE\n";
return EXIT_FAILURE;
}
std::string mode{ argv[2] };
if ( mode != "all" && mode != "top") {
std::cerr << "INVALID MODE\n";
return EXIT_FAILURE;
}
for (int i = 3; i < argc; ++i) {
std::fstream input_file{ argv[i] };
if (!input_file.is_open()) {
std::cerr << "BAD FILE \"" << argv[i] << "\"\n";
return EXIT_FAILURE;
}
}
}