hi, i'm workin on a lab for an intro to computer science class which deals with c++... one of the ten parts of it says the following

Read about the getline command for fetching an entire line from a input stream. Then make a text file of mixed words and numbers separated by commas. Write a function that takes an open stream as a parameter reads one line, and then prints each word or number from the line on a separate line (do not print any commas). Read five lines.


now i know how to use the getline command but i have no idea as to write the function that takes an open stream as a paramater ... here is my code from what i think i understood from the problem

#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;

int main(){

  ofstream fileWrittenInto;
  fileWrittenInto.open("fileUsedHere.csv");

  if(fileWrittenInto.fail()){
    cout<<"error opening fileUsedHere.csv"<<endl;
    exit(1);
  }//if open fileWrittenInto

  char c[20];
  fileWrittenInto << cin.getline(c,20);
  cout<<c<<"\n"<<endl;


  fileWrittenInto.close();


  /**
  ifstream someFileIn;
  someFileIn.open("lab09.2.cc.csv");

  if(someFileIn.fail()){
    cout<< "error opening the file requested\n";
    exit(1);
  }
  cout<<
  someFileIn.getline(c,20);
  **/

  return 0;
}//main



void somefunction(char * bs){//bs=open stream

  while(!bs.eof()){
    getline(bs,x,',');
    cout<<x<<endl;
  }

For your problem, you need to use a file stream variable that's for reading. The ofstream is for writing.

Once you've successfully opened the reading file stream, you can pass it to a function like any other parameter - BUT - it must be passed by reference.

Your file stream variables are used in the same way that you've been using cin and cout - you don't use them together like you do in line 17.

Here is an example of how to pass an ofstream.

#include <fstream>
using namespace std;

void foo (ofstream& outs);

int main ()
{
    ofstream outs ("file.txt");
    outs << "one";
    foo (outs);
    outs << "three";
    outs.close ();
    return 0;
}
  
  
void foo (ofstream& outs)
{
     outs << "two";
}

Use more compact, fast and robust stream control in the last function:

void somefunction(istream& bs)
{   
    string x;
    while (getline(bs,x,','))
        cout << x <<'\n';
    cout.flush();
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.