user7277330
user7277330

Reputation:

Writing to input and output files in c++

I cannot get my code to compile because it keeps telling me "error: no matching function for call" on line 16. Any advice? I am suppose to read the file and write all the vowels to an output file.

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

int main(){
    string filename;    // to hold the file name
    ifstream inputfile; // input to a file


    // Get the file name
    cout << "Enter a file name: ";
    cin >> filename;

    // Open the file
    inputfile.open(filename); // LINE 16

    char vowel; // to store the vowels
    ofstream outputfile; // to write to the file

    // open file
    outputfile.open("vowels_.txt");

    while(inputfile.get(vowel)){
        //If the char is a vowel or newline, write to output file.
        if((vowel == 'a')||(vowel == 'A')||(vowel =='e')||(vowel =='E')||(vowel =='i')||(vowel =='I')||(vowel =='o')||(vowel =='O')||(vowel =='u')||(vowel =='U')||(vowel =='\n') && !inputfile.eof())
            outputfile.put(vowel);

    }

    inputfile.close();
    outputfile.close();



}

Upvotes: 1

Views: 2350

Answers (1)

gsamaras
gsamaras

Reputation: 73444

Change this:

inputfile.open(filename);

to this:

inputfile.open(filename.c_str());

since filename is an std::string, and fstream::open takes const char* filename as a parameter.

Calling string:c_str returns const char* from std::string.


C++11 does not need this, since fstream::open is overloaded to take an std::string as well. Compile with -std=c++11 flag to enable c++11.


PS: Why don't the std::fstream classes take a std::string? (Pre-C++1)

Upvotes: 2

Related Questions