gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 05:42:44 24 4
gpt4 key购买 nike

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

谢谢

最佳答案

使用正则表达式: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++ - 如何从文件中识别数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36813434/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com