【问题标题】:Writing to input and output files in c++在 C++ 中写入输入和输出文件
【发布时间】:2017-09-13 05:31:32
【问题描述】:

我无法编译我的代码,因为它在第 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();



}

【问题讨论】:

  • 第 17 行是空行。
  • @immibis 第 16 行,抱歉
  • 我猜是 open() 调用。您需要传递一个字符指针,例如:inputfile.open(filename.c_str());
  • 或启用 C++11 或更高版本进行编译。

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


【解决方案1】:

改变这个:

inputfile.open(filename);

到这里:

inputfile.open(filename.c_str());

因为filenamestd::string,而fstream::openconst char* filename 作为参数。

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


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)

【讨论】:

  • 哦,好的。谢谢你
  • 我该怎么做?
  • 为什么您不能使用std::string有任何见解吗?
  • @Passer 你的意思是fstream::open?它与函数的原型、pre-C++11 和后期有关。
  • 是的,但我的意思是最初的考虑是什么使它缺乏这样的过载?
猜你喜欢
  • 2020-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-13
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多