2015-10-28 70 views
-1

这里的代码段是我的工作:CIN是跳过线

std::cout << "Enter title of book: "; 
std::string title; 
std::getline(std::cin, title); 
std::cout << "Enter author's name: "; 
std::string author; 
std::getline(std::cin, author); 
std::cout << "Enter publishing year: "; 
int pub; 
std::cin >> pub; 
std::cout << "Enter number of copies: "; 
int copies; 
std::cin >> copies; 

这是它运行时从本节的输出(加引号):

"Enter title of book: Enter author's name": 

怎么办我解决这个问题,以便我可以输入标题?

+0

(当前)两个答案提供了什么极有可能是解决问题的方法,但问题是缺少[MCVE的完整性要求(http://stackoverflow.com/help/mcve),不能与回答肯定。 [cin和函数getline跳过输入]的 – user4581301

+0

可能的复制(http://stackoverflow.com/questions/10553597/cin-and-getline-skipping-input) – Mykola

回答

1

我觉得你有一些输入之前,你不告诉我们。假设你可以使用std::cin.ignore()忽略从std::cin剩下的任何换行符。

std::string myInput; 
    std::cin >> myInput; // this is some input you never included. 
    std::cin.ignore(); // this will ignore \n that std::cin >> myInput left if you pressed enter. 

    std::cout << "Enter title of book: "; 
    std::string title; 
    std::getline(std::cin, title); 
    std::cout << "Enter author's name: "; 

现在它应该工作。

+0

这工作。现在我明白了。谢谢。 – Ricca

0

getline是换行分隔。然而,用std::cin之类的东西读取输入流中的换行符。作为this建议,由空格分隔,以换行符分隔输入切换时,要通过做cin.ignore清理从输入流中的所有换行符,例如:cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');。 (当然,我假设你getline之前蒸馏代码为MCVE时留出了cin)。