用c ++写入输入和输出文件

时间:2017-09-13 05:31:33

标签: c++ string function file-io compiler-errors

我无法让我的代码编译,因为它一直告诉我"错误:没有匹配的函数用于调用"在第16行。任何建议?我想读取文件并将所有元音写入输出文件。

#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();



}

1 个答案:

答案 0 :(得分:2)

改变这个:

inputfile.open(filename);

到此:

inputfile.open(filename.c_str());

因为filenamestd::stringfstream::open需要const char* filename作为参数。

致电string:c_strconst char*返回std::string

C ++ 11不需要这个,因为fstream::open被重载以获取std::string。使用-std=c++11标志进行编译以启用c ++ 11。

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