如何从文件中识别数据类型

时间:2016-04-23 16:33:25

标签: c++ string types int identify

所以我需要知道如何识别一行文本并输出它是什么类型的数据类型,如该行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");
}

由于

1 个答案:

答案 0 :(得分: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
}
...