std::variant

Lab C++ Advanced 30 points

Read tokens; store each as variant<long long, double, string> (integer, decimal or word). Use holds_alternative/get to print int N, double D (2 decimals) or text W, then the total of the numeric ones (2 decimals).

Input

n, then n tokens.

Output

n + 1 lines.

Example

Input

5
42
3.5
hello
-7
0.25

Output

int 42
double 3.50
text hello
int -7
double 0.25
total 38.75
Sample input available Sample output available
Editor
C++

Hints

A variant holds exactly one of its types at a time.

holds_alternative<T>(v) tells you which.

Solution explanation

variant is a type-safe union - the C++17 replacement for C unions.

Show solution
#include <iostream>
#include <iomanip>
#include <string>
#include <variant>
#include <vector>
using namespace std;

using Token = variant<long long, double, string>;

Token classify(const string &s) {
    bool digits = !s.empty(), dot = false;
    for (size_t i = 0; i < s.size(); i++) {
        char c = s[i];
        if (c == '-' && i == 0 && s.size() > 1) continue;
        if (c == '.' && !dot) { dot = true; continue; }
        if (c < '0' || c > '9') { digits = false; break; }
    }
    if (!digits) return s;
    if (dot) return stod(s);
    return stoll(s);
}

int main() {
    int n;
    cin >> n;
    double total = 0;
    cout << fixed << setprecision(2);
    for (int i = 0; i < n; i++) {
        string s;
        cin >> s;
        Token t = classify(s);
        if (holds_alternative<long long>(t)) {
            cout << "int " << get<long long>(t) << "\n";
            total += get<long long>(t);
        } else if (holds_alternative<double>(t)) {
            cout << "double " << get<double>(t) << "\n";
            total += get<double>(t);
        } else {
            cout << "text " << get<string>(t) << "\n";
        }
    }
    cout << "total " << total << "\n";
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD