简体   繁体   English

使用ifstream从文本文件读取

[英]Reading from text file using ifstream

I am trying to read from text file using ifstream object with extraction operator (>>) , and when I perform the following code , it is not reading at all ! 我试图使用带有提取运算符(>>)的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 ;
}

Is there any error in this code ? 这段代码有什么错误吗?

I doubt whether the program which you mentioned above is yours or not.Because i found a similar problem of yours in an e-book about file processing. 我怀疑您上面提到的程序是否是您的。因为我在关于文件处理的电子书中发现了您的类似问题。 I provide the link here, you can refer to it and correct your program if u want. 我在这里提供链接,如果您愿意,可以参考它并更正您的程序。

file processing.pdf 文件处理.pdf

What are those ends manipulators doing there? 那些ends操纵器在那里做什么? I would guess you should be outputing spaces instead. 我猜您应该改为输出空格。 And the obvious way to debug this is to write the code that creates the output file only and then see if it works by examining the output with a text editor. 调试此错误的明显方法是编写仅创建输出文件的代码,然后通过使用文本编辑器检查输出来查看其是否有效。

It's probably not reading because it's probably not writing. 它可能不是在读书,因为它可能不是在读书。 You didn't specify what you inputted into the console window when it asked you for input, but if you don't put in input in the format of 当控制台窗口要求您输入时,您没有指定输入到控制台窗口的内容,但是如果您未以以下格式输入内容:

integer string double

then nothing will be written to the file because cin<< will try to get a certain type and fail because the data doesn't match the type it wants. 则不会将任何内容写入文件,因为cin<<将尝试获取某种类型并由于数据与所需类型不匹配而失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM