c++ - 在C++中写入输入和输出文件

标签 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();



}

最佳答案

改变这个:

inputfile.open(filename);

为此:

inputfile.open(filename.c_str());

因为 filename 是一个 std::string,并且 fstream::openconst char* filename 作为参数。

调用 string:c_strstd::string 返回 const char*


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


附言:Why don't the std::fstream classes take a std::string? (C++1 之前)

关于c++ - 在C++中写入输入和输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46189521/

相关文章:

c++ - 是否有无限参数序列的模板?

c - strcmp 输出之谜 - strcmp 实际上是如何比较字符串的?

ruby - 如何按字母顺序对字符串的字符进行排序?

string - 如何将工期字符串格式化为天-小时-分钟的字符串?

javascript - Math.max.apply() 是如何工作的?

c - 了解在另一个 C 中调用一个函数

c++ - 我的算法只将第一个字写入文件?

c++ - 在C++11或更高版本中,有没有办法通过lambda实现单方法纯虚C++接口(interface)?

c++ - 在 C++ 中对 float 变量执行算术运算时,是否总是需要使用 float 文字?

c++ - C++ 中顶点/边的 VTK 自定义 ID