关于cout和cin的c++简单代码问题

C++ simple code issue about cout and cin

本文关键字:简单 代码 问题 c++ cout cin 关于      更新时间:2023-10-16

我有以下代码。一切都很好,但很不一样。我希望前三个cout <<一个接一个地出现,所以当控制台显示第一条消息时,用户输入值,然后下一个cout <<显示另一条消息,用户输入书名,然后第三个cout <<显示最后一条消息,用户输入年份。但是它显示了第一条消息,我输入了值,然后它一起显示了接下来的两条消息。为什么?

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    string AuthorName;
    string AuthorBook;
    string YearPublished;
    cout << "Please Enter the Author Name" << endl;
    cin >> AuthorName;
    cout << "Please enter the Author Book" << endl;
    cin >> AuthorBook;
    cout << "Please enter the year when the book was published" << endl;
    cin >> YearPublished;

    cout << setw(15) << "Author Name";
    cout << setw(15) << "Prominent Work";
    cout << setw(15) << "Year Published";
    cout << endl << endl;
    cout << setw(15) << AuthorName;
    cout << setw(15) << AuthorBook;
    cout << setw(15) << YearPublished;
    cout << endl << endl;
    return 0;
}

您需要使用getline(),因为c++使用cin在字符串的第一个空格处停止读取您的输入。