Hey guys. I have a horrible problem with passing strings in a function and using the string to open an input file. Could you guys give me a hand?

#include "pe3.h"

int main ()
{
    int ary[ SIZE ] ;
    ifstream inp ;
    string  iNam ;

    cout << "Input-file name:   " ; 
    getline( cin , iNam ) ; 

    openInFile( ifstream & inp , string iNam ) ;
    readData( ifstream & inp , int ary[] , int SIZE ) ;

    return 0 ;
}
int openFile( ifstream & inFile , string inFileName ) 
{ 
    inFile.open( inFileName.c_str() ) ; 
    if ( !inFile ) 
    { 
        cout << "\n!!  File '" << inFileName << "' not found -- check path !!" ;
        return 1 ; 
    } 
    return 0 ;
}

I get this error:
error C2275: 'std::ifstream' : illegal use of this type as an expression

at the openFile function call

Recommended Answers

All 4 Replies

openInFile( ifstream & inp , string iNam ) ;
    readData( ifstream & inp , int ary[] , int SIZE ) ;

Have you learned how to pass variables to functions yet? You don't put the type of the variable before the variable. Passing references doesn't mean you need & on the front-end, only for the function that receives the reference. Oh and by the way, you also don't put [] after an array -- just using the name of the array passes a pointer to the first element.

You also mistyped openFile .

Thus, your code becomes:

openFile(inp ,  iNam ) ;
    readData(inp ,  ary ,  SIZE ) ;
openInFile( ifstream & inp , string iNam ) ;
    readData( ifstream & inp , int ary[] , int SIZE ) ;

What are you trying to do here? call the openInFile and readData functions? don't include data types when passing function parameters

openInFile( inp , iNam ) ;
    readData( inp , ary[] , SIZE ) ;

Also make sure you've got a forward declaration for your openInFile function

great i got that part working, but now i'm getting error that saying things like ifstream undeclared identifier, infile undeclared identifier, etc...

here's my openInFile function

int openInFile( ifstream & inFile , string inFileName ) 
{ 
    inFile.open( inFileName.c_str() ) ; 
    if ( !inFile ) 
    { 
        cout << "\n!!  File '" << inFileName << "' not found -- check path !!" ;
        return 1 ; 
    } 
    return 0 ;
}

EDIT: forgot my header file, but still getting errors about overloading functions? error C2556: 'int openInFile(std::ifstream &,std::string)' : overloaded function differs only by return type from 'void openInFile(std::ifstream &,std::string)'

Change your function prototype from void openInFile() to int openInFile() .

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.