I have created a little console tool that simply does commands that you enter.
The commands are stored in a txt file. Right now I only got 2 commands: getTime
and getCommands
.
Pretty simple, but I'm not sure I'm doing anything the most optimal way, which is why I am asking here. I was thinking about creating a whole class to get the time but I wasn't sure that would make any sense (as it seems SYSTEMTIME
is already a class).
Also, I was thinking about the next command I would add is something where you can input "open 'file' ", where file is the program you want to open. I googled a bit and found a function called filefindnext
and filefindfirst
(to search for the file), but I'm not sure if this is the best way to do it? (I was also thinking about just adding a .txt file with the dir to the predefined files)
I hope you can help clear up my code and in general make my code better. I'm still fairly new to programming, so all constructive feedback is appreciated.
main.cpp (just a little test for my command class)
int main()
{
command list;
list.setCommandList();
list.printCommands();
while (1)
{list.getCommand();
}
}
commands.h
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class command
{
public:
command();
~command();
void printCommands();
string verifyCommand(string);
void getCommand();
void executeCommand(string);
void setCommandList();
private:
std::string userinput_;
std::ifstream file;
string *commandlist;
int cNr; //command number
};
commands.cpp
#include "commands.h"
#include "Time.h"
command::command(){
file.open("commands.txt");
cNr = 0;
}
command::~command()
{
file.close();
delete[] commandlist;
}
void command::printCommands()
{
string line;
cout <<"Command list:\n\n";
for (int i = 0;i<cNr;i++)
{
cout <<commandlist[i] <<endl;
}
cout <<endl;
}
void command::setCommandList()
{
int nrOfLines = 0;
string cline;
string line;
while (getline(file,cline))
{
nrOfLines++;
}
file.clear();
file.seekg(0, file.beg);
commandlist = new string[nrOfLines];
while (getline(file,line))
{
commandlist[cNr] = line;
cNr++;
}
}
string command::verifyCommand(string command)
{
string line;
for (int i = 0;i<cNr;i++)
{
if (command==commandlist[i])
return command;
}
return "";
}
void command::getCommand()
{
string userinput;
cout <<"Enter command:"<<endl;
cin >> userinput;
userinput_ = verifyCommand(userinput);
if (userinput_ == "")
{cout <<"Error, can“t find that command. Please try again"<<endl;
getCommand();
}
else
executeCommand(userinput_);
}
void command::executeCommand(string com)
{
if (com == "getTime")
{
cout << string( 100, '\n' ); //clear screen
SYSTEMTIME t;
GetLocalTime(&t);
cout<< "H:"<<t.wHour<<" M:"<<t.wMinute<<" S:"<<t.wSecond<<endl;
}
if (com == "getCommands")
{
cout << string( 100, '\n' );
printCommands();
}
}