如何重载cin到读取文件 [英] How to overload cin to read file
问题描述
可能重复:
操作输入文件流
C ++如何重载cin到读取文件
我尝试下面的操作符重载。
struct自己
{
string myname;
}
istream& operator>> (istream& stream,myself& mm)
{
cout< 输入我的名字:;
stream>> mm.myname;
return stream;
}
int main()
{
myself mm;
cin>> mm;
cout<< mm.myname;
}
及其工作,能够回应我实际类型。
现在我想继续使用
cout< ; 输入要读取的文件名:;
//假设用户类型为myfile.txt
cin>> readFile;
如何重载我的cin以使其读取文件。
考虑我的文件是
sometextdocument.txt,其中包含如
的数据Map2D,[3,2]
pre>
Dot3D,[25,-69,-33],[-2,-41,58]
Map3D,[6,9 ,-50]
Map2D,[3,2]
Dot3D,[7,-12,3],[9,13,68]
Map3D,[6,9,5]
Map2D,[3,2]
Dot3D,[70,-120,-3],[-29,1,268]
Dot3D,[7,12,3] -9,13,68]
Map3D,[1,3,8]
Dot2D,[5,7],[3,8]
然后我wanna
cout< 读取的记录数:<数字<< endl;
然后做一个返回流,我如何重载它工作作为cin读取文件解决方案尝试这样:希望这将是有用的
istream& ;> (istream& in,char * fname){
inFile.open(fname);
char ch1;
while(inFile.get(ch1)){
cout<< ch1;
}
}
Possible Duplicate:
Manipulate Input File StreamC++ How to overload cin to read file
I was trying the following with operator overload..
struct myself { string myname; } istream &operator>> (istream &stream, myself &mm) { cout << "Enter my name:"; stream >> mm.myname; return stream; } int main() { myself mm; cin >> mm; cout << mm.myname; }
and its work, able to echo out what i actually type.
Now i trying to proceed with
cout << "Enter file name to read: "; //assume user type myfile.txt cin >> readFile;
How do i overload my cin to make it read file.
Consider my file is something like
sometextdocument.txt that contains data like
Map2D, [3, 2] Dot3D, [25, -69, -33], [-2, -41, 58] Map3D, [6, 9, -50] Map2D, [3, 2] Dot3D, [7, -12, 3], [9, 13, 68] Map3D, [6, 9, 5] Map2D, [3, 2] Dot3D, [70, -120, -3], [-29, 1, 268] Dot3D, [7, 12, 3], [-9, 13, 68] Map3D, [1, 3, 8] Dot2D, [5, 7], [3, 8]
And then i wanna
cout << "Number of records read: " << number << endl;
then do a return stream, how do i overload it to work as cin read a file解决方案Try like this: hope it will be helpful
istream &operator>> (istream &in, char* fname){ inFile.open(fname); char ch1; while (inFile.get(ch1)) { cout<<ch1; } }
这篇关于如何重载cin到读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!