ifstream C ++的问题

时间:2012-09-05 17:38:08

标签: c++ ifstream

我对C ++和编程相对较新,所以我猜我的错误很简单。无论如何,我一直在从.txt文件中扫描DNA序列,我正在尝试对其进行编程,以便用户可以从命令行指定数据文件的名称。我包含整个函数以供参考,但是我得到的特殊问题是我无法让文件实际打开,程序总是返回“无法打开文件”消息。我遇到问题的部分(我认为)是循环的最后一部分,但我将整个函数作为参考。

int dataimport (int argc, char* argv[]){                                         

    vector<string> mutationfiles (argc -1); //mutationfiles: holds output file names
    vector<string> filenames (argc - 1);    //filenames:     holds input file names                                             

    if (argc > 1){
        for ( int i = 1; i < argc; ++i){
            string inputstring = argv[i];         //filename input by user
            filenames[i-1] = inputstring;         //store input filename in vector
            stringstream out;
            out << inputstring << "_mutdata.txt"; //append _mutdata.txt to input file names
            mutationfiles[i-1] = (out.str());     //store as output file name
            inputstring.clear();                  //clear temp string
        }
    }

    else{
        cout << "Error: Enter file names to be scanned" << endl;
        system("PAUSE");
        return EXIT_FAILURE;
    }


    for(int repeat = 0; repeat < argc; ++repeat){

        ifstream myfile;                                     //open input file
        myfile.open (filenames[repeat].c_str());

        ofstream myfile2;                                    //open output file
        myfile2.open (mutationfiles[repeat].c_str());

        string all_lines;

        if (myfile.is_open()){
            while ( myfile.good() ){                         //scan data
                getline (myfile,all_lines,'\0');
            }
            myfile.close();                                  //close infile
        }

        else{                                                //error message
            cout << "Unable to open file\n";
            system("PAUSE");
            return EXIT_FAILURE;
        }
    }
}

如果您需要任何其他信息或我应该研究的任何其他信息,请告诉我,以便我可以更好地帮助自己!

2 个答案:

答案 0 :(得分:1)

for(int repeat = 0; repeat < argc; ++repeat)

应该是

for(int repeat = 0; repeat < argc - 1; ++repeat)

除此之外,我看不到任何可能导致错误的事情。

如果您修复了此问题并仍然出错,我会尝试打印名称以确保两个向量的内容正确无误。

for(int repeat = 0; repeat < argc - 1; ++repeat)
{
    cout << filenames[repeat] << endl;
    cout << mutationfiles[repeat] << endl;
}

答案 1 :(得分:-1)

for ( int i = 1; i < argc; ++i)更改为for ( int i = 0; i < argc; i++)

filenames[i-1] = inputstring;更改为filenames[i] = inputstring;

mutationfiles[i-1]更改为mutationfiles[i]