c++ what would be a good way to read from text file?
Inside of the text file
-- start of text file ----
Physics 0 Chemistry 1 English 2
----end of text file
class Book { private: string title; int category; };
1) I want to store physics, chemisty, English to title; and 0,1,2 to a category;
ex, physics is category 0 chemisty is category 1 English is category 2
what I have...
string title; 开发者_JAVA百科 string number; if(book_input.is_open()) while(!book_input.eof()) { getline(book_input, title, '\n'); getline(book_input, number, '\n'); Book list(title, number); }
Is this a good way to store it??
That looks like a reasonable start, but your reading code should be:
while( getline(book_input, title, '\n') && getline(book_input, number, '\n') ) {
Book abook(title, number);
// do something with abook
}
Do not test against eof
, see this link for reasons.
You will have to do something with each book as it is read, and books constructor will have to convert its second parameter from a string to an int.
C++ can use value << stream
to input other types than string. An int
for instance.
You can use a similar method as (but backwards from) this example:
http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2
Is this a good way to store it??
Your class definition is fine. You'll also need to define a constructor, though:
class Book
{
public:
Book(string title, int category)
: title(title),
category(category)
{
}
// Todo: Maybe also some getters for title/category here...
private:
string title;
int category;
};
If you wanted, you could also use an enum
for category, though that would only work if you have a known limited set of categories. If you want to potentially expand your set of categories in the future, or you're uncertain, keep using an int. Though if you do, I'd recommend you call it categoryId
instead.
I think it is better if the constructor takes integer for the category
, for example by using stringstream
to convert to integer.
And assuming every title always has category number you can bypass check to the number like below:
while(getline(book_input,title)){
getline(book_input,strNumber);
stringstream ss(strNumber);
int number;
ss>>number;
Book aBook(title,number);
// code to process aBook
}
精彩评论