#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
void vowel(fstream a){
char ch;
int ctr = 0;
while(!a.eof()){
a.get(ch);
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'){
cout << ch;
ctr++;
}
}
cout << "Number of Vowels: " << ctr;
}
main(){
fstream a;
a.open("temp.txt", ios::in);
vowel(a);
return 0;
}
在这个简单的程序中,我试着计算temp.txt文件中的元音数量。但是,我收到了错误:
ios :: ios(ios&amp;)在功能上无法访问 fstream的:: fstream的(fstream的&安培;)
而是在函数本身打开文件来完成这项工作。 为什么会这样? 非常感谢
注意:
How do I use fstream (specifically ofstream) through a functions parameters
这里说,它应该像我一样努力。
瑞克
答案 0 :(得分:12)
fstream
对象不可复制。建议通过引用:fstream&
:
void vowel(fstream& a)
注意,您可以通过向构造函数提供相同的参数来避免对open()
的调用:
fstream a("temp.txt", ios::in);
并且不使用while(!a.eof())
,请立即检查读取操作的结果。仅当尝试读取超出文件中最后一个字符的内容时才会设置eof()
。这意味着,当!a.eof()
的上一次调用读取文件中的最后一个字符时,get(ch)
将为真,但后续get(ch)
将失败并设置eof,但代码不会被注意到失败,直到它再次处理ch
,即使读取失败。
示例正确的结构:
while (a.get(ch)) {
答案 1 :(得分:3)
您需要通过参考传递fstream
:
void vowel(fstream& a){ .... }
// ^ here!
答案 2 :(得分:2)
试试这个。而不是发送文件计算元音排队。
#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
int vowels=0;
void vowel(string a){
char ch;
int ctr = 0;
int temp=0;
for(temp=0,temp<a.length();temp++){
ch=a.at(temp);
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U'){
cout << ch;
ctr++;
}
}
vowels+=ctr;
}
main(){
fstream a;
a.open("temp.txt", ios::in);
string temp;
while(getline(a,temp))
{
vowel(temp);
function2(temp);
function3(temp);
... so on for more then one functions.
}
vowel(a);
return 0;
}
如果你想传递文件,那么使用上面的ans。(通过引用传递fstream)。
答案 3 :(得分:-1)
你可以做很多事情来解决你的问题其中2个是在全局范围内声明ifstream 并且在全局范围内声明你的方法。
C ++
#import<stuff>
//other imports here
ifsteam in_stream;
void method_Name(ifstream in_stream,string user_input);
int void main(){
string user_input;
instream.open("dogs.txt");//you can open your file here or in the method
//Code here
cin>> user_input;
method_Name(user_input);
return 0;
}
void method_Name(){
//or even better opening file here
//do stuff
}
在您的情况下,您也可以使用'&amp;'将其传递给方法在ifstream之后就像 Vowel(ifstream&amp; a);
我已经在我的一些程序中使用了第一个实例来打开.csv文件并从中读取没有遇到任何问题。顺便说一下,确保使用类似的东西检查文件是否实际打开了
if (in_stream.fail( )){//Checking to see if file failed to open
cout << "Input file opening failed.\n";
exit(EXIT_FAILURE);
}