簡體   English   中英

輸入一個整數,然后輸入一個帶有空格的字符串 c++

[英]Entering an Integer then a string with spaces c++

我怎么能 cin 一個整數然后一個字符串“帶空格”這是我的代碼

int x;string s;
    cout<<"Enter Integer"<<endl;
    cin>>x;
    cout<<"Enter the string with spaces"<<endl;
    //if i used cin>>s here then it will not read all the text because it has spaces 
    // is i used getline(cin,s); then it will not read any thing  

您可能遇到的問題是cin >> x讀取您鍵入的數字的數字,而不是以下換行符。 然后,當您執行cin >> s讀取字符串時,輸入處理器會看到換行符並僅返回一個空字符串。

解決方案是使用旨在讀取整行輸入的函數,例如std::getline 不要將提取運算符>>用於交互式輸入。

要讀取帶空格的字符串,請使用std::getline

但!

注意當>>遇到分隔符時會發生什么。 它停止並在流中留下分隔符。 只要您只使用>>因為>>將丟棄所有空格,這不是問題。 std::getline將捕獲該空格,一個常見的用例是

user types in number and hits enter
user types in string and hits enter

那么會發生什么? >>提取數字並在遇到空格時停止。 通過在流中按回車鍵,將行尾放入流中。 std::getline出現,它看到的第一件事是......行尾。 std::getline存儲一個空字符串並立即返回。 現在程序處理一個空字符串,並且仍然期望輸入字符串的用戶輸入了一個將由將來讀取的字符串,這可能會將輸入流放入錯誤案例中,並且肯定會給用戶帶來驚喜。

一個常見的解決方案是使用ignore(numeric_limits<streamsize>::max(), '\\n'); 在提示用戶輸入和調用std::getline之前,使用流中的任何數據,直到並包括行尾。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM