Reputation: 3843
For some reasons the string cin.getline (temp.Autor, 20)
is ignored. Please, have a look at the output
Could you help me understand why?
struct BOOK {
char Autor[20];
char Title[50];
short Year;
int PageCount;
double Cost;
};
void new_book()
{
BOOK temp;
system("cls");
cout <<"ENTERING NEW BOOK: " << endl <<endl;
cout <<"Input the author: ";
cin.getline (temp.Autor, 20);
cout <<"Input the title: ";
cin.getline (temp.Title, 50);
cout <<"Input the year of publishing: ";
cin >> temp.Year;
cout <<"Input the number of pages: ";
cin >> temp.PageCount;
cout <<"Input the cost: ";
cin >> temp.Cost;
cout << endl;
print_book(temp);
system("pause");
}
Upvotes: 0
Views: 261
Reputation: 361442
"It is not me who invented such a structure. And I can't change it.".
Whoever has come up with this struct, is a bad bad guy. He is an enemy of C++, especially Modern C++. Even if he has a PhD in Computer Science, he is a bad bad guy, and doesn't know where to start studying C++. He might be good in other concepts of CS, but he is not good at all in C++. Because of such instructors, C++ has got the bad name, when C++ is not that bad.
Now coming back to the struct. Show him this struct:
struct Book
{
std::string Author;
std::string Title;
short Year;
int PageCount;
double Cost;
};
And ask him what is wrong with this struct, especially with the std::string
members? Ask him for reason(s) as to why you shouldn't prefer this instead of char-array. Why he thinks raw-char-array is better than std::string
?
Whatever reason(s) he come up with, just tell him : FOR GOD SAKE, LEARN REAL C++.
There is NOTHING wrong in learning raw-char-array, pointers, or memory-management. The point is that these concepts should be taught at the later stage of your course, not in the beginning. I repeat NOT IN THE BEGINNING. Your assignment does show that it is the beginning of the course. So in the beginning, the students should be taught std::string
, std::vector
and other containers, and algorithms from the standard library.
Once the students learn these, they can go ahead with how they're implemented, where comes the details such as raw-array, pointers, memory-management, and hell lots of things. These are advanced topics which come with problems as well as idiomatic solutions, most popular being RAII which solves the memory-management elegantly. That is to say, a student should NEVER be taught about new
and delete
alone, he should be taught RAII along with it.
Now coming back to HOW to read data into the members of the previously defined struct:
Book book;
//assuming each value is on its own line!
if ( !std::getline(std::cin, book.Author) )
{
std::cerr << "Error while reading Author \n";
}
//read data into other members
Hope that helps.
Upvotes: 6
Reputation: 5002
The cin
function stops reading when it finds a space. Use getline
to read the author and book names.
Read this question for more information:
Why does the program loop infinitely?
Upvotes: 3