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

时间:2014-06-10 16:44:16

标签: c++ iostream

我有以下代码。一切都很好,但完全不同。我希望前三个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;
}

1 个答案:

答案 0 :(得分:3)

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