由于某些原因,string cin.getline (temp.Autor, 20)它被忽略了.请看看输出
你能帮我理解为什么吗?
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");
}
Run Code Online (Sandbox Code Playgroud)
"发明这种结构不是我.而且我无法改变它."
无论谁想出这个结构,都是一个坏人.他是C++的敌人,特别是Modern C++.即使他拥有计算机科学博士学位,他也是一个坏人,并且不知道从哪里开始学习C++.他可能在CS的其他概念方面表现出色,但他在C++中并不擅长.由于有这样的教师,当C++ 没有 那么糟糕时,C++就有了坏名声.
现在回到结构.向他展示这个结构:
struct Book
{
std::string Author;
std::string Title;
short Year;
int PageCount;
double Cost;
};
Run Code Online (Sandbox Code Playgroud)
并问他这个结构有什么问题,尤其是std::string成员?问他原因(S) ,为什么你不应该喜欢这个,而不是字符数组.为什么他认为raw-char-array比std::string?
无论他提出什么理由,只要告诉他:为了上帝,学习真正的C++.
学习raw-char-array, 指针或内存管理没有任何问题.关键是这些概念应该在课程的后期教授,而不是在开始时教授.我重复不要在开始.您的作业确实表明它是课程的开始.因此,在开始阶段,要教过的学生std::string,std::vector和其他容器,并从标准库算法.
一旦学生们学会了这些知识,他们就可以继续学习它们的实现方式,其中包括原始数组,指针,内存管理以及很多东西等细节.这些是带有问题的高级主题以及惯用的解决方案,最受欢迎的是RAII,它优雅地解决了内存管理问题.也就是说,一个学生不应该是教给new和delete 孤独,他应该教RAII 一起吧.
现在回到如何将数据读入先前定义的结构的成员:
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
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.