gpt4 book ai didi

c++ - 两个 cin/cout 语句合并为一个

转载 作者:太空狗 更新时间:2023-10-29 22:55:44 26 4
gpt4 key购买 nike

<分区>

我刚刚开始尝试从 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

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