0

So I need to know how to identify a line of text and output what kind of data type it is, like if the line says 123, it should be output as 123 int.

Right now, my program only identifies boolean, string, and char. How do I get it to tell me if it is an int or a 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");
}

Thanks

nalzok
  • 14,965
  • 21
  • 72
  • 139
  • You could use a regular expression? if it matches \d+\.\d+ then we have a double and if it matches \d+$ then we have an int – saml Apr 23 '16 at 16:37
  • There is an infinite set of numbers that can be either integer or floating point. The value 123 can be a floating point value or an integer. Some algorithms use the decimal point, so that 123 is integer and 123. is a floating point. Some implementations require scientific notation: 1.23E+2. – Thomas Matthews Apr 23 '16 at 17:28

1 Answers1

1

Use regex: 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
    Reminder: Not all versions of C++ have the regular expression features. Many people posting to StackOverflow are still using TurboC++, which definitely doesn't support the C++ regular expressions. – Thomas Matthews Apr 23 '16 at 17:29
  • How does your regular expression differentiate between an integer and a floating point value? This is what the OP wants. I'm asking because the value 456 can be either integer or floating point and the regular expression may be a bit complicated. – Thomas Matthews Apr 23 '16 at 17:30
  • The standard way should be preferred. If a compiler does not support standard features, there are libraries providing them. Parsing without regex is painful, so you better know it exists and learn it. –  Apr 23 '16 at 17:34
  • The question is "How to idenfity data type from file", not "how to match floats and integers" so my example for booleans still answers the question. It's trivial to match numeric strings with regex. –  Apr 23 '16 at 17:36