Unable to use getline with an istream object

slipbits 16 Reputation points
2022-10-09T13:25:30.093+00:00

Win7-64
VS 2019 Version 16.11.19

I'm trying use getline in a function using a passed istream object. The compiler produces an error and when I look at the two getline functions in istream I can't see what I've done wrong. It works when I use cin but not when I use an istream object.

I am trying to use the same function to input data from either a file or cin. The function code is the same in either case, but the input source is different. Can this be done?

--- code sample ---

# include <istream>  
using namespace std;  

void funct(istream^ in) {  
    char chr[513];  
    istream* x = new ifstream();  
    in.getline(chr, 512);        // has      compiler errors  
    cin.getline(chr, 512);      // has no compiler errors  
    x->getline(chr, 512);      // has no compiler errors  

   // results using std::getlne()  
   string str;  
   getline(in, str);               // has        compiler errors  
   getline(cin, str);             // has  no  compiler errors  
}  

stack overflow https://stackoverflow.com/questions/71919623/issues-with-passing-fstream-as-an-input-using-getline shows that it works in a Linux environment.

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,637 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 114.7K Reputation points
    2022-10-09T13:50:21.32+00:00

    Try changing the definition to void funct( istream& in ) and also include the <iostream>, <fstream> and <string> files.