【问题标题】:How to identify data type from file如何从文件中识别数据类型
【发布时间】:2016-08-17 05:48:41
【问题描述】:

所以我需要知道如何识别一行文本并输出它是什么样的数据类型,比如如果该行显示123,它应该输出为123 int

目前,我的程序仅识别 booleanstringchar。如何让它告诉我它是int 还是double

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");
}

谢谢

【问题讨论】:

  • 你可以使用正则表达式吗?如果它匹配 \d+\.\d+ 那么我们有一个双精度,如果它匹配 \d+$ 那么我们有一个 int
  • 有一组无限的数字,可以是整数或浮点数。值 123 可以是浮点值或整数。有些算法使用小数点,所以 123 是整数,123. 是浮点数。一些实现需要科学记数法:1.23E+2。

标签: c++ string types int identify


【解决方案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
}
...

【讨论】:

  • 提醒:并非所有版本的 C++ 都有正则表达式功能。许多在 StackOverflow 上发帖的人仍在使用 TurboC++,它肯定不支持 C++ 正则表达式。
  • 您的正则表达式如何区分整数和浮点值?这就是OP想要的。我问是因为值 456 可以是整数或浮点数,正则表达式可能有点复杂。
  • 应该首选标准方式。如果编译器不支持标准功能,则有提供它们的库。没有正则表达式的解析很痛苦,所以你最好知道它的存在并学习它。
  • 问题是“如何从文件中识别数据类型”,而不是“如何匹配浮点数和整数”,所以我的布尔示例仍然回答了这个问题。用正则表达式匹配数字字符串很简单。
猜你喜欢
  • 1970-01-01
  • 2015-04-16
  • 2010-11-03
  • 2022-01-05
  • 1970-01-01
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
相关资源
最近更新 更多