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

时间:2018-05-24 05:22:39

标签: c++ cin cout

我刚刚开始尝试从C语言进入C ++,它的类似程度足以让人很容易接受,但却略有不同,有点令人气愤(我想念你的malloc)。无论如何,我的问题在于我正在尝试使用C ++中的结构,并且对每本书调用一次enterBookInformation函数。但是,在第二次调用函数时,标题和作者的前两个​​cin / cout语句结合并转化为

Enter Title of Book: Enter Author of Book: 

第一次调用函数的效果很好。我认为它可能与缓冲区刷新(?)有关,就像我在C中的经验和这个bug的行为一样,但我不会有明确的线索,也无法在网上找到与我的问题有关的任何内容。这是我的代码:

//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

1 个答案:

答案 0 :(得分:1)

问题在于您将getline()cin >>的通话混合在一​​起。后者不会消耗尾随换行符。

你可以替换

std::cin >> year;

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

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

还有其他方法可以处理它。关键是您需要使用尾随换行符。