2015-10-28 121 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)。