Passing a file into a function

时间:2015-07-29 00:25:28

标签: c++ function ifstream

I'm trying to create a program that passes a file to a function. The function is supposed to detect how many lines are in my file. I don't think I'm passing the file correctly into my function, I've tried several different ways. Any help will be greatly appreciated.

<div id="topbar">
    <div id="topbar_wrapper">
        <ul id="mainmenu">
            <li><a href="#">Home</a></li><li>
            <a href="#">Search</a></li><li>
            <a href="#">Sort By &#9660</a>
                <ul id="sortmenu">
                    <li><a href='#'>Song</a>
                        <ul id="sortsongmenu">
                            <li><a href='#'>A to Z</a></li><li>
                            <a href='#'>Z to A</a></li>
                        </ul>
                    </li><li>   
                    <a href='#'>Artist</a></li><li>
                    <a href='#'>Album</a></li><li>
                    <a href='#'>Genre</a></li><li>
                    <a href='#'>BPM</a></li><li>
                    <a href='#'>Release Date</a></li>
                </ul>
            </li><li>
            <a href="#">Add Song</a></li><li>
            <a href="#">Contant Us</a></li>
        </ul>
    </div>
</div>

1 个答案:

答案 0 :(得分:2)

Two problems with the function. First, you should pass the stream by reference. Second, you just forgot to initialise your counter.

// > [ [ 'A', 'T' ], [ 'A', 'T' ], [ 'C', 'G' ] ]

The other thing is you're passing int num_of_lines( ifstream &file ) { int cnt3 = 0; string str; while( getline(file, str) ) cnt3++; return cnt3; } to it (which is a string) instead of file. Change the call to:

ifs