【发布时间】:2018-05-24 05:22:39
【问题描述】:
我刚刚开始尝试从 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;
}
我尝试将奥赛罗和白鲸记作为书籍的输出现在看起来像这样:
./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
【问题讨论】: