两个 cin / cout 语句合并为一个

Two cin / cout statements being combined into one

我刚刚开始尝试从 C 进入 C++,它非常相似,很容易上手,但在一些令人恼火的方面有微妙的不同(我想念你的 malloc)。无论如何,我的问题是我正在尝试使用 C++ 中的结构,并且 enterBookInformation 函数被调用两次,每本书调用一次。但是,在第二次调用该函数时,标题和作者的前两个​​ cin / cout 语句合并并变成

Enter Title of Book: Enter Author of Book: 

函数的第一次调用工作正常。我认为这可能与缓冲区刷新(?)有关,就像我在 C 中的经验和此错误的行为一样,但我没有明确的线索,也无法在网上找到与我的问题相关的任何内容。这是我的代码:

//struct_example.cpp

#include <iostream>
using namespace std;

#include <iomanip>
using std::setw;

#include <cstring>

struct books_t enterBookInformation(struct books_t book, unsigned short counter);
void printBooks(struct books_t book1, struct books_t book2);

struct books_t {
    char title[50];
    char author[50];
    int year;
};

int main(void) 
{
    struct books_t book1;
    struct books_t book2;
    book1 = enterBookInformation(book1, 1);
    book2 = enterBookInformation(book2, 2);
    printBooks(book1, book2);
}

struct books_t enterBookInformation(struct books_t book, unsigned short counter)
{
    char title[50], author[50];
    int year;
    std::cout << "Enter Title of Book " << counter << ": ";
    std::cin.getline(title, sizeof(title));
    std::cout << "Enter Author of Book " << counter << ": ";
    std::cin.getline(author, sizeof(author));
    std::cout << "Enter the Year of Publication " << counter << ": "; 
    std::cin >> year;
    strcpy(book.title, title);
    strcpy(book.author, author);
    book.year = year;
    return book;
}

void printBooks(struct books_t book1, struct books_t book2)
{
    std::cout << setw(15) << "Book 1 Title: " << setw(25) << book1.title << endl;
    std::cout << setw(15) << "Book 1 Author: " << setw(25) << book1.author << endl;
    std::cout << setw(15) << "Book 1 Year: " << setw(25) << book1.year << endl;
    std::cout << setw(15) << "Book 2 Title: " << setw(25) << book2.title << endl;
    std::cout << setw(15) << "Book 2 Author: " << setw(25) << book2.author << endl;
    std::cout << setw(15) << "Book 2 Year: " << setw(25) << book2.year << endl;
}

我尝试将 Othello 和 Moby Dick 作为书籍输入时的输出现在如下所示:

./struct_example 
Enter Title of Book 1: Othello
Enter Author of Book 1: William Shakespeare
Enter the Year of Publication 1: 1603
Enter Title of Book 2: Enter Author of Book 2: Herman Melville
Enter the Year of Publication 2: 1851
 Book 1 Title:                   Othello
Book 1 Author:       William Shakespeare
  Book 1 Year:                      1603
 Book 2 Title:                          
Book 2 Author:           Herman Melville
  Book 2 Year:                      1851

问题是您将对 getline() 的调用与 cin >> 混合调用。后者不消耗尾随换行符。

你可以替换

std::cin >> year;

{
    std::string s;
    std::getline(std::cin, s)
    year = std::stoi(s);
}

执行 #include <string> 以完成上述工作。

您还可以通过其他方式处理它。关键是你需要消耗尾随换行符。