c ++:在单独的情况下忽略cin.getline

时间:2013-01-08 07:10:15

标签: c++ getline

由于某些原因,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");
}

2 个答案:

答案 0 :(得分:6)

  

“发明这种结构不是我。而且我无法改变它。”

无论谁想出这个结构,都是一个坏人。他是C ++的敌人,特别是Modern C ++。即使他拥有计算机科学博士学位,他也是一个坏人,并且不知道从哪里开始学习C ++。他可能在CS的其他概念方面表现出色,但他在C ++中并不擅长。由于这些教师,当C ++ 时,C ++的名字不好。

现在回到结构。向他展示这个结构:

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

问他这个结构有什么问题,特别是对std::string成员?向他询问 reason(s)为什么你不应该更喜欢而不是 char-array 。为什么他认为 raw-char-array std::string好?

无论他提出什么理由,只要告诉他:上帝保佑,学习真正的C ++。

学习 raw-char-array 指针内存管理时没有错。关键是这些概念应该在课程的后期教授,而不是在开始时教授。我重复不要在开始。您的作业确实显示它是课程的开头。因此,在开始时,应该向学生讲授std::stringstd::vector和其他容器以及标准库中的算法。

一旦学生学习了这些内容,他们就可以继续实施这些内容,其中包括原始数据,指针,内存管理以及地狱之类的细节。这些高级主题存在问题以及惯用解决方案,最受欢迎的是RAII,它优雅地解决了内存管​​理问题。也就是说,学生不应该只学习newdelete ,他应该在{/ 3}} 一起学习

现在回到如何读取数据到以前定义的结构的成员中:

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

希望有所帮助。

答案 1 :(得分:3)

cin函数在找到空格时停止读取。使用getline阅读作者和书名。

阅读此问题以获取更多信息:

Why does the program loop infinitely?