【问题标题】:Title of text file as an input of function文本文件的标题作为函数的输入
【发布时间】:2015-07-26 10:42:37
【问题描述】:
double function(){
string filename;
ifstream fileIN;
fileIN.open("Layout.txt");
}

我有一个读取 txt 文件并将数据保存到数组中的函数。 我现在想要做的是我想把“Layout.txt”作为函数的输入。 它应该看起来像

double function(string Layout.txt){
string filename;
ifstream fileIN;
fileIN.open(Layout.txt);
}

显然它不起作用..请帮助!

【问题讨论】:

    标签: c++ text ifstream


    【解决方案1】:

    变量名不能包含.。它们可以包含字母、数字和下划线 (_),并且不能以数字开头。所以你可以做的是

    void function(string filename) {
        ifstream fileIN;
        fileIN.open(filename);
    }
    

    【讨论】:

      【解决方案2】:

      我认为您混淆了变量名、字符串值和文件名。

      您显然需要的是这样的函数:

      double function(string const& filename){
          ifstream fileIN;
          fileIN.open(filename);
          // ...
      }
      

      或在 C++11 之前的版本中:

      double function(string const& filename){
          ifstream fileIN;
          fileIN.open(filename.c_str());
          // ...
      }
      

      那你这样称呼它:

      function("Layout.txt");
      

      将文件名硬编码到明显通用函数的变量名中是没有意义的。您显然想将function 用于许多不同的文件,那么为什么要使用使其看起来好像只适用于一个特定文件的变量名呢?

      您的函数很可能只需要使用“Layout.txt”文件。在这种情况下,您根本不需要参数:

      double function(){
          ifstream fileIN;
          fileIN.open("Layout.txt");
          // ...
      }
      

      【讨论】:

        猜你喜欢
        • 2019-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-06
        • 2013-02-08
        • 2013-07-10
        • 1970-01-01
        • 2020-07-03
        相关资源
        最近更新 更多