C ++文件输入循环难度大?

时间:2015-01-27 04:15:48

标签: c++ loops file-io

我是一个非常新手的程序员,我在使用文件输入循环时遇到了麻烦。

我正在阅读一系列书籍及其相关标题,封面类型,页面和权重。我目前花了一个多小时试图找出如何写这个,以便循环继续到下一组数据(标题后跟封面类型,然后是页数,最后是重量)。

文本文件包含以下内容:

The Human Use of Human Beings
0
200   
8.0    
Utopia 
0    
176    
4.8    
Hackers    
0    
520   
22.4    
The Information    
1    
544    
33.6   
Sterling's Gold    
1    
176    
8.0

这是我的main.cpp:

using namespace std;

int main()
{
    const string FILENAME("books.txt");

    ifstream input(FILENAME);

    if( input.good() )
    {
        while( !input.eof() )
        {
            string name;
            int type;
            int pages;
            float ounces;
            getline( input, name );
            input >> type >> pages >> ounces;
            input.ignore(INT_MAX, '\n');  

            Book newBook(name, static_cast<Type>(type), pages, ounces);

            cout << newBook.formatReportLine() << endl; 
        }
    }
    else
    {
        cout << "File not found: " << FILENAME << endl;
    }

    return 0;
}

这是我的book.cpp文件:

//Constructor
Book::Book( const string& name, Type type, int pages, float ounces )
{
    bName = static_cast<string>(name);
    bType = type;
    bPages = pages;
    bOunces = ounces;
}

//Default Constructor
Book::Book() {
    bName = "";
    bType = UNKNOWN;
    bPages = 0;
    bOunces = 0.0f;
}

float Book::getWeightLbs()
{
    const float OUNCES = 16.0f;
    return bOunces / OUNCES;
}

string Book::getTypeName()
{
    return TYPE_WORDS[bType];
}

string Book::formatReportLine() 
{
    stringstream reportLine;
    reportLine << Book::getName() << setw(10) << "| Type: " << Book::getTypeName() << setw(10) << "Pages: " << Book::getPages()<< setw(10) 
    << "Weight: " << Book::getWeightLbs(); 

    return reportLine.str();
}

最后是book.h

using namespace std;

enum Type
{
    UNKNOWN = -1,
   PAPERBACK,
    HARDBACK
};

const string TYPE_WORDS[] = { "Paperback", "Hardback" };

class Book
{
public:
    Book();
    //constructor
    Book( const string& name, Type type, int pages, float ounces );
    //destructor
    ~Book(){};

    string formatReportLine();  
    float getWeightLbs();  
    string getTypeName();  

    //accessors
    string getName(){ return bName; };
    Type getType(){ return bType; };
    int getPages(){ return bPages; };
    float getOunces(){ return bOunces; };

private:
    string bName;  //name of the book
    Type bType;  //the type of book 
    int bPages;  //how many pages the book contains
    float bOunces;  //how much the book weighs in ounces
};

目前它正确打印出第一行,然后无限制地循环第一本书的封面类型,页面和重量。我花了很长时间试图弄清楚这个。非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

将您的循环更改为:

string name;
int type;
int pages;
float ounces;

while(getline(input, name) >> type >> pages >> ounces)
{
     // do something with name, type, pages, and ounces
}

如已关联,请参阅 "while( !feof( file ) )" is always wrong