2012-01-31 102 views
1

我正在寫一個非常簡單的程序,我想從標準輸入流(鍵盤)獲取用戶輸入,然後根據我遇到的輸入做些事情。然而,問題在於有時輸入將是一個數字(雙精度),而其他情況則是字符串。我不確定爲了正確分析它需要什麼方法調用(可能類似於Java中的Integer.parseInt)。如何解析來自標準輸入流的用戶輸入?

這裏是我想要做什麼一些pseduocode:

cin >> input 
if(input is equal to "p") call methodA; 
else if(input is a number) call methodB; 
else call methodC; 
+0

什麼是「輸入」? 'char'或'std :: string'? – Phonon 2012-01-31 16:47:35

+0

我不知道...什麼會使這個程序最容易實現...所以字符串我想 – Nosrettap 2012-01-31 16:50:50

回答

3

我覺得這是你所需要的:

#include <iostream> 
#include <sstream> 
#include <string> 
using namespace std; 

void a(string& s){ cout << "A " << s << endl; } 
void b(double d){ cout << "B " << d << endl; } 
void c(string& s){ cout << "C " << s << endl; } 

int main() 
{ 
    std::string input; 
    cin >> input; 
    if (input == "p") 
     a(input); 
    else 
    { 
     istringstream is; 
     is.str(input); 
     double d = 0; 
     is >> d; 
     if (d != 0) 
      b(d); 
     else 
      c(input); 
    } 
    return 0; 
} 

希望這有助於;)

0
std::string input; 
std::cin >> input; 
if(input =="p") f(); 
else if(is_number(input)) g(); 
else h(); 

現在實現is_number()功能:

bool is_number(std::string const & s) 
{ 
    //if all the characters in s, are digits, then return true; 
    //else if all the characters, except one, in s are digits, and there is exactly one dot, then return true; 
    //else return false 
} 

自己實現這個功能,因爲它似乎是功課。你也可以考慮像數字可能以+-標誌開頭的情況。

0

通常的解決方案,我用的是讀取輸入的一行(使用 std::getline而非>>)並解析它,因爲我會在任何 語言— boost::regex在這裏非常有用;如果你確信 你可以指望C++ 11,它是std::regex(我認爲這幾乎是 與Boost相同)。所以你最終得到類似的東西:

std::string line; 
if (! std::getline(std::cin, line)) { 
    // Error reading line (maybe EOF). 
} else { 
    if (regex_match(line, firstFormat)) { 
     processFirstFormat(line); 
    } else if (regex_match(line, secondFormat)) { 
     processSecondFormat(line) ; 
    } ... 
} 
+0

'if(!std :: string(std :: cin,line))''?你的意思是'if(!std :: getline(std :: cin,line)'' – Nawaz 2012-01-31 17:02:00

+0

@Nawaz肯定,我會編輯這個帖子來修復它(我認爲這就是所謂的thinko,而不是一個錯字)更大的規模。) – 2012-01-31 17:27:55