【问题标题】:Using fstream Object as a Function Parameter使用 fstream 对象作为函数参数
【发布时间】:2013-01-24 14:25:25
【问题描述】:
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>

void vowel(fstream a){
    char ch;
    int ctr = 0;
    while(!a.eof()){
        a.get(ch);
        if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'){
            cout << ch;
            ctr++;
        }
    }
    cout << "Number of Vowels: " << ctr;
}

main(){
    fstream a;
    a.open("temp.txt", ios::in);
    vowel(a);
return 0;
}

在这个简单的程序中,我试图计算文件 temp.txt 中大写元音的数量。但是,我收到了错误:

ios::ios(ios &) 在函数中不可访问 fstream::fstream(fstream&)

而不是在函数本身中打开文件来完成这项工作。 为什么会这样? 非常感谢

注意:

How do I use fstream (specifically ofstream) through a functions parameters

这里说,它应该按照我尝试的方式工作。

瑞克

【问题讨论】:

    标签: c++ function fstream


    【解决方案1】:

    fstream 对象不可复制。而是通过引用传递:fstream&amp;:

    void vowel(fstream& a)
    

    请注意,您可以通过向构造函数提供相同的参数来避免调用 open()

    fstream a("temp.txt", ios::in);
    

    不要使用while(!a.eof()),立即检查读取操作的结果。 eof() 仅在尝试读取文件中的最后一个字符之后才会设置。这意味着 !a.eof() 将在上一次调用 get(ch) 从文件中读取最后一个字符时为真,但随后的 get(ch) 将失败并设置 eof 但代码在处理完之前不会注意到失败@ 987654331@ 再次即使读取失败。

    正确结构示例:

    while (a.get(ch)) {
    

    【讨论】:

    • 感谢您的解释。避免使用 open()... 我知道。谢谢。但是 eof() 有什么问题呢?用什么代替?
    • 太棒了。这就是为什么当我试图读取包含类的文件并显示内容时,我两次得到最后一个输出。我找到了一种解决方法,方法是在再次输出之前检查 if (a.eof()),而不是在 while 循环中检查它。非常感谢hmjd
    • @hmjd 我有点困惑。什么更有效,通过流或字符串行。
    • 非常感谢您。对于其他初学者:fstram&amp; 进入函数的定义,而不是在你调用它的时候。
    【解决方案2】:

    您需要通过引用传递fstream

    void vowel(fstream& a){ .... }
    //                ^ here!
    

    【讨论】:

      【解决方案3】:

      试试这个。而不是发送文件,而是按行计数元音。

      #include <iostream.h>
      #include <fstream.h>
      #include <stdlib.h>
      int vowels=0;
      void vowel(string a){
          char ch;
          int ctr = 0;
      int temp=0;
          for(temp=0,temp<a.length();temp++){
              ch=a.at(temp);
              if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'){
                  cout << ch;
                  ctr++;
              }
          }
          vowels+=ctr;
      }
      
      main(){
          fstream a;
          a.open("temp.txt", ios::in);
      
      string temp;
      while(getline(a,temp))
      {
      vowel(temp);
      function2(temp);
      function3(temp);
      
      
      ... so on for more then one functions.
      
      }        
      vowel(a);
          return 0;
          }
      

      如果你想传递文件然后使用上面的ans。(通过引用传递fstream)。

      【讨论】:

      • 这也可以。但是我打算编写多个函数(计算元音,计算单词数,句子数等),并且不想在每个函数中打开文件。您的解决方案会,但会导致我为每个函数一次又一次地编写 while(getline(a, string temp)) 循环。谢谢
      • 文件只打开一次!从循环内部调用其他函数。
      • 但它会得到每一行,和O/P。示例:元音数:5 [对于 l1] 字数:2 [对于 l1] 元音数:6 [对于 l2] 字数:3.... 不,错误。对不起。它也会起作用。谢谢
      猜你喜欢
      • 2013-01-03
      • 1970-01-01
      • 2014-06-28
      • 2011-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      相关资源
      最近更新 更多