我无法编译我的代码,因为它在第 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::open
将 const char* filename
作为参数。
调用 string:c_str
从 std::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/