Is it possible to create a variable within a program (while its running).

The problem I am trying to Solve:

In school I created a cashmachine emulator. The thought then dawned on me, what If I wanted different user abilities within my cash machine program (Ie. only the manager would be able to define prices, and sales values).

Now I realize I could design the program with a set amount of users, but is there a way to input a new usewr (and variables containing the users data) while the program is running? (Ie. create an entirely new variable that was not defined or even used before.)

Dani AI

Generated

Short answer: you cannot add new source-code variable names while a program is running, but you can create new objects (instances) at runtime and keep them in dynamic containers. For your cash‑machine emulator this is exactly the right approach: represent each user as a single object (username, role, permissions) and add instances when the administrator creates new accounts.

Building on replies already here: was right to point at using a constructor to build an object; pointed to keeping a list and appending to it; and was correct about persisting user details to a file. Combined: define a User type, keep users in a container (vector or map), let the admin create a User and push it into the container, and save/load the collection to disk at program start/exit.

Example pattern (illustrative):

struct User {
  std::string name;
  enum Role {Admin, Manager, Employee} role;
  User(std::string n, Role r): name(std::move(n)), role(r) {}
};

std::vector<User> users;       // in-memory
users.emplace_back("alice", User::Manager);  // create at runtime

// save simple CSV
std::ofstream out("users.csv");
for (auto const& u : users) out << u.name << ',' << int(u.role) << '\n';

Practical tips and cautions:

  • Do role checks instead of separate switches: allow price changes only if role == Manager or Admin.
  • Persist data (CSV, JSON, or SQLite) so new users survive program restart.
  • Never store plaintext passwords; use salted hashes (use a library for bcrypt/Argon2).
  • If multiple processes/users might touch the file, use a proper DB (SQLite) or file locking.
  • Refactor away from goto/switch spaghetti into functions and small classes — it will make adding users and permissions trivial.

This approach scales: add roles, permissions, or attributes without changing source variable names — just add fields or rules and keep manipulating objects at runtime.

Recommended Answers

All 5 Replies

Not sure what you're asking for, but it seems like you could simply ask for the values and then use an appropriate constructor to create an object that defines the user...

>is there a way to input a new usewr while the program is running?
Yes, of course. Just maintain a list of valid users, and when adding a new user, append to the list. Unfortunately, without further detail about how you're going about things, I can't be more specific.

is there a way to input a new usewr while the program is running?
Yes, of course. Just maintain a list of valid users, and when adding a new user, append to the list. Unfortunately, without further detail about how you're going about things, I can't be more specific.

Here is some of the basic code:

/*
Name: Adam Adamowicz
Id #: 114861
Lab Section: G
Lab: 5, Program: 2.0
This program will demonstrate the basic programming needed for a fastfood resteraunt
computer program.
*/

#pragma hdrstop
#include <condefs.h>
#include <stdio.h>

//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
        int drinkchoice;
        char mealchoice;
        float mealprice, mealgst, drinkprice, drinkgst, total;

        printf ("McKrusty's Main Meals:\nA. Krusty Burger\nB. Krusty Fries\nC. Krusty Buns\nEnter your choice here:  ");
        scanf (" %c", &mealchoice);

        printf ("\nMcKrusty's Drinks: \n1. Krusty Pop \n2. Krusty Juice \nEnter your choice here:  ");
        scanf (" %d", &drinkchoice);

        switch(mealchoice)
                {
                case 'A': mealprice = 4.25;
                        break;
                case 'B': mealprice = 1.75;
                        break;
                case 'C': mealprice = 3.50;
                        break;
                default : mealprice = 0.0;
                          break;
                }

        switch(drinkchoice)
                {
                case 1: drinkprice = 1.50;
                        break;
                case 2: drinkprice = 2.25;
                        break;
                default : drinkprice = 0.0;
                          break;
                }

        mealgst = ( mealprice * .07);
        drinkgst = ( drinkprice * .07) ;
        total = mealprice + drinkprice + drinkgst + mealgst ;

        printf ("\nPrice of Krusty meal:  \t$%5.2f\n", mealprice);
        printf ("Krusty meal GST:  \t$%5.2f\n", mealgst);
        printf ("Price of Krusty drink:  $%5.2f\n", drinkprice);
        printf ("Krusty drink GST:  \t$%5.2f\n", drinkgst);
        printf ("\nTotal: \t\t\t$%5.2f\n", total);
        printf ("\n\nPress \"Enter\" to quit.\n");

        getchar ();
        getchar ();
        return 0;
}

And for the change calculator

/*
Name: Adam Adamowicz
Id #: 114861
Lab Section: G
Lab: 6, Program: 1.0
This program will emulate a vending machine.
*/
#pragma hdrstop
#include <condefs.h>
#include <stdio.h>
#include <math.h>

//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{       int choice;
        float price, money;
        printf ("Your choices are: \n 1. Chocolate Bar ($1.25)\n 2. Granola Bar ($1.50)\n 3. Crispy Square ($0.75)\nEnter your choice here: ");
        scanf (" %d", &choice);
        printf ("\n");

        switch (choice)
                {
                case 1: price = 1.25; break;
                case 2: price = 1.50; break;
                case 3: price = 0.75; break;
                default: price = 0.00; break;
                }
        while (price > 0)
                {
                printf ("Enter $%4.2f: ", price);
                scanf (" %f", &money);
                price -= money;
                }

        price = fabs(price);

        printf ("\nYou get $%4.2f back in change.", price);

        printf ("\n\nPress \"Enter\" to quit.");
        getchar();
        getchar();
        return 0;
}

So, what I have done, is combined the two programs, the choices of the first one with the change aspect of the second.

Now I have also included a switch statement for the users (admin manager or employee, default is exit. ) the switch is inside of a do while statement (if true program runs through again if false returns to switch. (it is unstructered progamming but I did use goto statements)

Now that is the very easy part, the problem is this, I realize that if I wanted to add more employees I could simply add another line to the switch, and anothert variable to the definition portion at the beggining of the program, but what I was wondering is if it is possible to create this new employee and create a new variable to store them in from with in the program (ie, the administrator section of the program)

you can do it but with a different approch. you need to store your users' details(what they can do, and can't). then when you need to add another type of user, just append these new users' details to the file.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.