簡體   English   中英

使用ifstream從文本文件讀取

[英]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 ;
}

這段代碼有什么錯誤嗎?

我懷疑您上面提到的程序是否是您的。因為我在關於文件處理的電子書中發現了您的類似問題。 我在這里提供鏈接,如果您願意,可以參考它並更正您的程序。

文件處理.pdf

那些ends操縱器在那里做什么? 我猜您應該改為輸出空格。 調試此錯誤的明顯方法是編寫僅創建輸出文件的代碼,然后通過使用文本編輯器檢查輸出來查看其是否有效。

它可能不是在讀書,因為它可能不是在讀書。 當控制台窗口要求您輸入時,您沒有指定輸入到控制台窗口的內容,但是如果您未以以下格式輸入內容:

integer string double

則不會將任何內容寫入文件,因為cin<<將嘗試獲取某種類型並由於數據與所需類型不匹配而失敗。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM