2016-04-23 60 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