Solved: C++ and Functions..

Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

Codiah

Thread Starter
Joined
Sep 27, 2008
Messages
116
Ok, so i'm having a bit of trouble at the moment.. i understand what functions are and how to set up the bast of the function... my problem is when it comes to actually using the function i've set up... i'm writing my first c++ program with numerous functions in it and i want to be able to utalize them all like commands... i know how to do "choice" in c++ but i want to make input in small commands not just single letters... but its a little lost on me at the moment... i'm trying my best to avoid the goto command and keep everything in a modular form, i just need to know how to connect the peices.. any help would be great..
 
Joined
Sep 14, 2005
Messages
919
i know how to do "choice" in c++ but i want to make input in small commands not just single letters... but its a little lost on me at the moment.
Just use std::string and input a command using std::cin. Heres an example program I just wrote. It has two commands: print and exit. Typing "print" executes the print command (just displays a string), typing "exit" terminates the program. Hope this gives you some ideas:

Code:
#include <iostream>
#include <string>

std::string commands[] = {
	"print",
	"exit"
};

enum {
	CMD_PRINT,
	CMD_EXIT
};

void cmdPrint () {

	std::cout << "command print executed" << std::endl;
}

bool cmdTest (std::string& cmd) {

	bool ret=true;

	if (cmd==commands[CMD_PRINT])
		cmdPrint();
	else if (cmd==commands[CMD_EXIT])
		;
	else
		ret=false;

	return ret;
}

int main()
{
	std::string strCmd;
	std::cout << "Type \"exit\" to quit\n" << std::endl;

	do {
		std::cout << "command >";
		std::cin >> strCmd;

		if (! cmdTest (strCmd) )
			std::cout << "unkown command \'" << strCmd << "\', ignored" << std::endl;

	}
	while ( strCmd != commands[CMD_EXIT]);
}
 

Codiah

Thread Starter
Joined
Sep 27, 2008
Messages
116
Perfect, exactly what I've been looking for, once again.. thanks... wasn't to sure i was gonna get a replay back on this one...
 
Joined
Sep 14, 2005
Messages
919
I would have replied a little earlier but didnt quite know what you were looking for :) Glad it helps though :D
 
Status
This thread has been Locked and is not open to further replies. Please start a New Thread if you're having a similar issue. View our Welcome Guide to learn how to use this site.

Users Who Are Viewing This Thread (Users: 0, Guests: 1)

As Seen On
As Seen On...

Welcome to Tech Support Guy!

Are you looking for the solution to your computer problem? Join our site today to ask your question. This site is completely free -- paid for by advertisers and donations.

If you're not already familiar with forums, watch our Welcome Guide to get started.

Join over 807,865 other people just like you!

Latest posts

Top