2016-04-23 63 views
0

所以我需要知道如何識別一行文本並輸出它是什麼類型的數據類型,例如如果行說123,它應該輸出爲123 int如何從文件中識別數據類型

現在,我的程序只識別boolean,stringchar。我如何得知它是否是intdouble

int main() { 
    string line; 
    string arr[30]; 
    ifstream file("pp.txt"); 
    if (file.is_open()){ 
     for (int i = 0; i <= 4; i++) { 
      file >> arr[i]; 
      cout << arr[i]; 
      if (arr[i] == "true" || arr[i] == "false") { 
       cout << " boolean" << endl; 

      } 
      if (arr[i].length() == 1) { 
       cout << " character" << endl; 

      } 
      if (arr[i].length() > 1 && arr[i] != "true" && arr[i] != "false") { 
       cout << " string" << endl; 
      } 
     } 
     file.close(); 
    } 
    else 
     cout << "Unable to open file"; 
    system("pause"); 
} 

感謝

+0

你可以使用正則表達式?如果它匹配\ d + \。\ d +,那麼我們有一個double,如果匹配\ d + $,那麼我們有一個int – saml

+0

有一個無限的數字集可以是整數或浮點數。值123可以是浮點值或整數。有些算法使用小數點,所以123是整數,123是浮點數。某些實現需要科學記數法:1.23E + 2。 –

回答

1

使用正則表達式:http://www.cplusplus.com/reference/regex/

#include <regex> 
std::string token = "true"; 
std::regex boolean_expr = std::regex("^false|true$"); 
std::regex float_expr = std::regex("^\d+\.\d+$"); 
std::regex integer_expr = std::regex("^\d+$"); 
... 
if (std::regex_match(token, boolean_expr)) { 
    // matched a boolean, do something 
} 
else if (std::regex_match(token, float_expr)) { 
    // matched a float 
} 
else if (std::regex_match(token, integer_expr)) { 
    // matched an integer 
} 
... 
+1

提醒:並非所有版本的C++都具有正則表達式功能。發佈到StackOverflow的許多人仍在使用TurboC++,它肯定不支持C++正則表達式。 –

+0

您的正則表達式如何區分整數和浮點值?這是OP想要的。我在問,因爲值456可以是整數或浮點數,正則表達式可能有點複雜。 –

+0

標準方式應該是首選。如果編譯器不支持標準功能,則有庫提供它們。 解析無正則表達式是痛苦的,所以你最好知道它存在並學習它。 – Rei