gpt4 book ai didi

c++: cin.getline 在一个单独的案例中被忽略

转载 作者:太空宇宙 更新时间:2023-11-04 14:55:59 25 4
gpt4 key购买 nike

由于某些原因,string cin.getline (temp.Autor, 20) 被忽略了。请看一下 the output你能帮我理解为什么吗?

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");
}

最佳答案

"It is not me who invented such a structure. And I can't change it.".

谁想出了这个结构,谁就是坏蛋。他是C++的敌人,尤其是Modern C++。就算是计算机博士,也是个坏蛋,不知道从哪里开始学C++。他可能擅长CS的其他概念,但他对C++一点都不擅长。因为有这样的导师,C++ 有了坏名声,而 C++ 不是 坏。

现在回到结构。给他看这个结构:

struct Book 
{
std::string Author;
std::string Title;
short Year;
int PageCount;
double Cost;
};

然后问他这个结构有什么问题,尤其是 std::string 成员?问他原因,为什么你不应该喜欢这个而不是char-array。为什么他认为 raw-char-arraystd::string 更好?

无论他想出什么理由,只要告诉他:看在上帝的份上,学习真正的 C++。

学习原始字符数组指针内存管理并没有错。关键是这些概念应该在类(class)的后期而不是一开始就教授。我不在开始时重复一遍。您的作业确实表明这是类(class)的开始。所以一开始要教给学生std::stringstd::vector等容器,以及标准库中的算法。

一旦学生学会了这些,他们就可以继续了解它们的实现方式,其中包括原始数组、指针、内存管理等细节。这些是伴随问题而来的高级主题以及惯用解决方案,最流行的是 RAII,它优雅地解决了内存管​​理问题。也就是说,永远不应该教学生 newdelete ,他应该被教 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

希望对您有所帮助。

关于c++: cin.getline 在一个单独的案例中被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14209903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com