Order variables alphabetically

Hi, we have a class project to slove linear equations, but first I have to print it in the proper form. if the user's input like this
3x2+2x1+4x3=16
it should be
2x1+3x2+4x3=16
I believe I will use a "for loop" and "substr" but can't write the code. any help?
I assume 3x2 means 3x2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Example program
#include <iostream>
#include <sstream>
#include <string>
#include <array>
#include <algorithm>

struct Term {
    Term() : coefficient(0), variable(0), subscript(0) {}
    Term(int coefficient, char variable, int subscript)
    : coefficient(coefficient), variable(variable), subscript(subscript) {}
    int coefficient;
    char variable;
    int subscript;
    
    struct Comparer
    {
        inline bool operator() (const Term& t1, const Term& t2)
        {
            return (t1.subscript < t2.subscript);
        }
    };
};

std::ostream& print_term(std::ostream& os, const Term& term, bool first)
{
    if (term.coefficient != 0)
    {
        if (!first && term.coefficient > 0)
            os << "+";
        os << term.coefficient << term.variable << term.subscript;
    }
    return os;
}

constexpr int Num_Terms = 3;

std::ostream& operator<<(std::ostream& os, const std::array<Term, Num_Terms>& terms)
{
    if (Num_Terms == 0) return os;

    print_term(os, terms[0], true);
    for (int i = 1; i < Num_Terms; i++)
    {
        print_term(os, terms[i], false);
    }
    return os;
}

int main()
{
    std::string input = "3x2+2x1+4x3=16";

    // process input LHS
    std::istringstream ss(input);    
    std::array<Term, Num_Terms> terms;
    for (int i = 0; i < Num_Terms; i++)
    {
        ss >> terms[i].coefficient;
        ss.get(terms[i].variable);
        ss >> terms[i].subscript;
    }
    
    // process input RHS
    std::string rhs;
    getline(ss, rhs);
    
    std::sort(terms.begin(), terms.end(), Term::Comparer());
    
    // 2x1+3x2+4x3=16
    std::cout << terms << rhs << std::endl;
}
Last edited on
Topic archived. No new replies allowed.