2017-08-16 79 views
-1

我試圖把輸入變量數量的字符串和numbers.Found該解決方案link變量輸入:如何採取從標準的C++

我想這對於數字

#include<iostream> 
using namespace std; 
int main(){ 
    int np; 
    while (cin>>np){ 
     cout << np<<endl; 
    } 
    return 0; 
} 

字符串:

#include<iostream> 
#include<string> 
using namespace std; 
int main(){ 
    string line; 
    while (getline(cin, line)){ 
     cout << line <<endl; 
    } 
    return 0; 
} 

但是,當我運行代碼,甚至如果我只是按回車,它不會出現循環。循環應該終止,如果只是一個回車鍵被按下,但沒有發生。

請提供建議如何實現此功能。

+5

回車鍵仍然是一個有效的字符串。 –

+0

那麼如果沒有其他人離開,如何停止輸入? – ssharma

+1

取決於操作系統。如果內存服務,在Windows中它是'Ctrl + Z',在Unix中它是'Ctrl + D'。 – Abstraction

回答

2

你可以寫

while (std::getline(std::cint, line) && !line.empty()) { 
    // ... 
} 

只有不斷循環當獲取字符串是空的。