【问题标题】:How to make input text file a constructor parameter? c++ [closed]如何使输入文本文件成为构造函数参数? c++ [关闭]
【发布时间】:2018-08-06 14:36:10
【问题描述】:

我正在尝试将输入文件(应该由用户选择)作为构造函数参数。问题是我的代码不起作用。经过一些研究,我的猜测是那种类型的参数,即 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 );
}

【问题讨论】:

  • "问题是我的代码不起作用。" 这样的声明是无用的信息。请详细说明如何它不起作用。
  • 你的意思是在你的 main 方法而不是你的 Parameters 方法中提示输入文件名吗?就目前而言,fileName 参数没有任何作用。
  • @AlgirdasPreidžius 当我运行代码并将示例文件的名称作为输入时,它甚至没有打开。
  • @auburg 我希望用户选择将作为构造函数参数的文件名。您能否进一步解释一下为什么 fileName 参数无用?
  • 因为它什么也没做——你的 main 方法中应该有提示符(cin >> filename)——像现在这样传递一个空字符串有什么用?

标签: c++ file input parameters constructor


【解决方案1】:

您打开文件两次:

  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;

【讨论】:

    猜你喜欢
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    相关资源
    最近更新 更多