2013-04-14 68 views
1

我想檢查一個空行作爲執行特定操作的輸入。我嘗試使用cin.peek()並檢查它是否等於'\ n',但它沒有任何意義。使用cin檢查空行

a

b

c

空行(在這裏,我要履行我的動作)

a

我曾嘗試這樣的代碼:

char a,b,c; 
cin>>a; 
cin>>b; 
cin>>c; 
if(cin.peek()=='\n') { 
cout<<a<<endl; 
cout<<b<<endl; 
cout<<c<<endl; 
} 
+0

['的std :: getline'](http://en.cppreference.com/w/cpp/string/basic_string/getline)? – Xymostech

+0

@Xymostech,如果您要求使用getline,請檢查其長度。我更喜歡使用「cin >> a」,因爲我的輸入將在一行中是多個變量。 –

+0

您是否正在閱讀文件? – 2013-04-14 00:47:10

回答

5

使用getline,然後處理字符串。如果用戶輸入空行,則字符串將爲空。如果他們沒有,你可以對字符串做進一步的處理。你甚至可以把它放在istringstream,並把它看作是來自cin

下面是一個例子:

std::queue<char> data_q; 
while (true) 
{ 
    std::string line; 
    std::getline(std::cin, line); 

    if (line.empty()) // line is empty, empty the queue to the console 
    { 
     while (!data_q.empty()) 
     { 
      std::cout << data_q.front() << std::endl; 
      data_q.pop(); 
     } 
    } 

    // push the characters into the queue 
    std::istringstream iss(line); 
    char ch; 
    while (iss >> ch) 
     data_q.push(ch); 
} 
+0

請問您可以寫一個簡單的例子來更多地理解您並說明如何從字符串中提取我的輸入 –

+1

@ AbdEl-RahmanEl-Tamawy:我添加了一個看起來與您所做的相似的示例。 –

+0

如果輸入字符是空格''會怎麼樣?此代碼是否會跳過此空間或將其作爲輸入? std :: istringstream iss(line); char ch; while(iss >> ch) data_q.push(ch); –