如何使输入文本文件成为构造函数参数? C ++

时间:2018-08-06 14:36:10

标签: c++ file input parameters constructor

我正在尝试创建应该由用户选择的输入文件,即构造函数参数。问题是我的代码无法正常工作。经过一些研究,我的猜测是参数的类型,即 string fileName 可能是错误的。我还尝试放置 fstream fileName ,但这也没有用。我期待听到任何有关如何使代码正常工作的建议。 这是代码:

using namespace std;
class Parameters
{
public:
   Parameters( string fileName);
};
Parameters::Parameters(string fileName)
{           
    cout<< "Give name of the file:" << endl;
    cin >> fileName;
    fstream plik( fileName.c_str() );
    plik.open( fileName.c_str(), ios::in | ios::out );

    if( plik.good() == true )
    {
        cout << "file is open" << endl;          
    } 
        else 
        cout << "error" << endl;    
    }

int main()
{
    Parameters s("");
    getch();
    return( 0 );
}

1 个答案:

答案 0 :(得分:2)

您要打开文件两次:

  1. fstream plik( fileName.c_str() );
  2. plik.open( fileName.c_str(), ios::in | ios::out );

您应该将其更改为仅打开一次,例如:

fstream plik;
plik.open( fileName.c_str(), ios::in | ios::out );

或:

fstream plik( fileName.c_str(), ios::in | ios::out );

如果仍然无法打开文件,则应检查原因。 您可以使用以下命令打印错误说明:

cout << "error: " << strerror(errno) << endl;