[英]Reading from text file using ifstream
我试图使用带有提取运算符(>>)的ifstream对象从文本文件中读取内容,当我执行以下代码时,它根本无法读取!
#include <iostream>
#include <fstream>
#include <iomanip>
void outputLine( int account, const char *const name , double balance )
{
cout << left << setw( 10 ) << account << setw( 13 ) << name
<< setw( 7 ) << setprecision( 2 ) << right << balance << endl;
} // end function outputLine
int main()
{
ofstream outfile("client.txt",ios::out);
if (!outfile)
{
cout << "the file is not opened .. " << endl ;
exit(1);
}
int account;
char name[30];
double balance;
while (cin >> account >> name >> balance)
{
outfile << account << ends << name << ends << balance << endl ;
cout << "? " ;
}
outfile.close();
ifstream inFile;
inFile.open( "client.txt",ios::in);
if ( !inFile )
{
cerr << "File could not be opened" << endl;
exit( 1 );
} // end if
cout << left << setw( 10 ) << "Account" << setw( 13 )
<< "Name" << "Balance" << endl << fixed << showpoint;
while (inFile >> account >> name >> balance )
{
outputLine( account, name, balance );
}
return 0 ;
}
这段代码有什么错误吗?
我怀疑您上面提到的程序是否是您的。因为我在关于文件处理的电子书中发现了您的类似问题。 我在这里提供链接,如果您愿意,可以参考它并更正您的程序。
那些ends
操纵器在那里做什么? 我猜您应该改为输出空格。 调试此错误的明显方法是编写仅创建输出文件的代码,然后通过使用文本编辑器检查输出来查看其是否有效。
它可能不是在读书,因为它可能不是在读书。 当控制台窗口要求您输入时,您没有指定输入到控制台窗口的内容,但是如果您未以以下格式输入内容:
integer string double
则不会将任何内容写入文件,因为cin<<
将尝试获取某种类型并由于数据与所需类型不匹配而失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.