使用 ifstream 从文本文件读取

Reading from text file using ifstream

本文关键字:文件 读取 文本 ifstream 使用      更新时间:2023-10-16

我正在尝试使用带有提取运算符(>>)的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<<将尝试获取某种类型并失败,因为数据与它想要的类型不匹配。