mercredi 4 avril 2018

why wont this program compile with user input for filename

i copied this problem straight out of the textbook tony gaddis c++, and it won't compile. compiler is gcc 5.4.0. this is the my program:

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

int main() 
{
    string fileName;
    char ch;
    fstream file;

    cout << "enter a filename: ";
    cin >> fileName;

    file.open(fileName, ios::in);

    if(file)
    {
        file.get(ch);

        while(file)
        {
            cout << ch;

            file.get(ch);
        }
        file.close();
    } 
    else 
        cout << fileName << " could not be opened.\n";
    return 0;
}

again, i copied this straight out of the text. in fact it fails immediately after this point:

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

int main() 
{
    string fileName;
    char ch;
    fstream file;

    cout << "enter a filename: ";
    cin >> fileName;

    file.open(filename, ios::in);

    // comment everything else out and compile still fails

    return 0;
}

this is the errors spit in the console:

chp12chal.cpp: In function ‘int main()’:
chp12chal.cpp:15:32: error: no matching function for call to ‘std::basic_fstream<char>::open(std::
__cxx11::string&, const openmode&)’     
file.open(filename, ios::in);
                           ^
In file included from chp12chal.cpp:2:0:
/usr/include/c++/5/fstream:1001:7: note: candidate: void std::basic_fstream<_CharT, _Traits>::open
(const char*, std::ios_base::openmode) [with _CharT = char; _Traits = std::char_traits<char>; std:
:ios_base::openmode = std::_Ios_Openmode]       
       open(const char* __s,
       ^
/usr/include/c++/5/fstream:1001:7: note: no known conversion for argument 1 from ‘std::__cxx11::
string {aka std::__cxx11::basic_string<char>}’ to ‘const char*’

so im not sure what all of that means. though i only started having this problem once i started taking user input as a variable for the input stream. when i simply code in the path of the file to open it works fine. also, i know fileName and filename are not spelled the same, but thats the way it is done throughout the book in numerous examples so im leaving that as so. could this be a compiler specific issue?

Aucun commentaire:

Enregistrer un commentaire