How to create a class that can use the same function to show different messages

I want to create a class that can use the same function to show different messages from the program, like error messages to show in the console using one output function. I'm unsure how to begin doing this, I have some ideas but cant seem to figure out the rest of the code, I havent been programming for the past 3 or 4 months so im a little rusty., I dont really have any code that attempts this but here is this:

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
#include <iostream>
#include <string>
#include <vector>

using namespace std;

void EnterText(string str);
void ShowText(string str);

class DisplayText
{
    public:
        
    
    private:
};

int main()
{
    string str;

    EnterText(str);
    ShowText(str);

    return 0;
}

void EnterText(string str)
{
    cout << "Enter some text" << endl;
    getline(cin, str);

    ShowText(str);
}

void ShowText(string str)
{
    cout << str << endl;
}
Hi Chay,

I imagine you want to have a container that has a short string which is a look up value for the long string which is the full error message.

So a natural container might be std::map http://www.cplusplus.com/reference/map/map/

because it stores a key and value information which could be the look up value and error message respectively.

The key must be unique.

So you would need to declare a std::map<std::string, std::string> ErrorMap and put some info into it.

Then have a
1
2
3
std::string getLongErrorMsg (const std::string& ShortError,
                                           const std::map<std::string, std::string>& ErrorMap
                                           )


function that calls std::map::find and returns the LongErrorMsg , which can be printed with std::cout.

http://www.cplusplus.com/reference/map/map/find/

An issue with that, is that the short error message being searched for must match the key value in the map container exactly.


A more complicated arrangement might search for a partial string in the Error message, but that might involve using regex which is more tricky.

Good Luck !!
Well, it would be for any string in the code, couldnt i make a vector of strings in a class, and use that vector function to write strings and push them back, and then get them when I need them?
That would be the second more complex option I mentioned. It's the looking up of the string that is the issue. Using a regex might not be too bad, might get away with a * wildcard.

There is probably a larger question about processing of errors: What is the situation there?

It might possibly involve using exceptions or Design Patterns.
Well, I was thinking what I could do is just use the vector to store all strings, and then whenever i need a string, i can just call the vector and output the string i want at whaterver index location its being stored, I came up with this but it doesnt quite work, I cant get it to output:

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
#include <iostream>
#include <string>
#include <vector>

using namespace std;

void EnterText();
void ShowText();

class DisplayText
{
    public:
        vector<string> StrVectorFunction(vector<string> str_vector, string str)
        {
            getline(cin, str);
            str_vector.push_back(str);

            return str_vector;
        }

    private:
        vector<string> str_vector;
        string str;
};

int main()
{
    EnterText();
    ShowText();

    return 0;
}

void EnterText()
{
    cout << "1" << endl;

    vector<string> str_vector;
    string str;

    DisplayText dt;

    cout << "Enter some text" << endl;

    dt.StrVectorFunction(str_vector, str);

    ShowText();
}

void ShowText()
{
    cout << "2" << endl;

    vector<string> str_vector;
    string str;

    DisplayText dt;
    dt.StrVectorFunction(str_vector, str);

    for(int i = 0; i < str_vector.size(); i++)
    {
        cout << str_vector[i] << endl;
    }
}
Well, now I am a little confused: It looks like you want to print all the strings - lines 60 to 63.

Never mind the code (It's full of problems), I think the larger questions are more important.

If you just want to print one of them - how do you know which one you want? That's what I meant when I asked for context of how this is all coming about.

How is an error detected, that is before you get to here?

How is that realisation of an error translated into some value that can be used to look up an error in a list?
well that was just a test, idk how to get it to where i want it to be. Like i said, im pretty rusty, I'm re reading my C++ Books.

Sometimes i feel like just giving up on it all together, i've been learning for 7 years and i've gotten pretty much nowhere, But I love doing it though, so its hard to quit.
Last edited on
well that was just a test, idk how to get it to where i want it to be.


Don't worry about that for now, can you answer my other questions?

But I love doing it though, so its hard to quit.


Don't feel you need to quit, IMO there are a couple of things:

1. Coding: get the basics right, understand how it works, remember it. Move upwards from there.

2. Design: Have a clear idea of what you want to achieve. Write it down on paper. What is the input? What is the output? Write those two things down. How are you going to store the information? Choose a type that might be suitable - std::string , std::vector<std::string> , std::vector<YourOwnClass> Break the process down into individual steps - start out general then gradually refine things.

Also, you mentioned in the past that you are a visual learner: So draw pictures of how things work. Get this: that's what developers do. It's formalised into a thing called UML. I am not saying you should rush off and learn that - for now just draw a picture that makes sense for you.

I personally find as well as diagrams, I learn things better if I write things down. It's too easy for things to bounce off if it is only being read or listened to. I used to have a Lecturer that would read verbatim the lecture notes displayed on an overhead projector. So I would hear it, see it, and write it down, then check that I had written the formula correctly. After 1 hour and seven or eight pages of notes, it was amazing how much one remembered.

Anyway, can you answer my previous questions? I could write some code for you, but it depends on what those answers are.
Im not really sure anymore, i dont really think this idea was very solid to begin with.
actually you know what, i'm going to try to do this, this is my problem, i find something to do and when its hard i quit, how am i supposed to learn if i quite at the first sign of trouble? So to answer the questions:

"If you just want to print one of them - how do you know which one you want? That's what I meant when I asked for context of how this is all coming about. "

Hmm, im not quite sure, thats another problem i have, I think of how i want stuff to work, but i cant really verbalize it so its difficult to write down. I knew how i wanted it to work but cant really remember now.

EDIT: Ok so i remember what i wanted to do, so any string in the code, I want to pass through 1 function that outputs text, how it figures out what string to output will most likely be hard coded, so we could do something like assign a number to each string? idk. So basically instead of using cout every single time i want text to appear, i can use the function, which i guess is pretty much the same thing so idk where i was going with this lol, I guess its just having one function do the work is my main goal, so the strings would have to be entered into the function then cleared so that there is no text left in it. hopefully that answers your question.
Last edited on
Ok, cool - that's the way :+D

I would try the simpler of my two ideas first, this one:

http://www.cplusplus.com/forum/beginner/186072/#msg907473

Have a bash, see how you get along.

Some tips:

Make sure you read up on the documentation for each thing that you use. Not only to get the syntax correct, but to understand how the thing works.

Try adapting an example form the documentation.

Draw pictures, write things down.

Write pseudo-code. I know it seems like a real drag, but I sincerely think that could be just the thing to help you get things right.

I will write some code this evening, just to set up the map to put the strings in - so that can be a starting point for you.
so we could do something like assign a number to each string?


I was going to have 2 strings, a short one the key to look up, and a long one the actual full error message. I put both of these into a std::map<std::string, std::string>

I have been playing a bit of TombRaider, so I have some ideas from there.

So if the std::map conceptually looked like this:

1
2
3
4
"Door" , "Door Locked, need to take care of other things first\n"
"Switch", "Switch disabled until some other levers are pulled\n"
"Gear", "Gear cog missing, you need to look for them elsewhere\n"
"Jag", "Danger: Jaguar Thralls about\n"


Then you might call the Search function with "Gear" as the argument, and it would print "Gear cog missing, you need to look for them elsewhere\n"

The main problem with this is: if one puts in "gear" say, the whole thing fails, because it needs an exact match. Nevertheless it will be a reasonable start.

Using a regex will help a lot, we wouldn't have the short string at all, and one should be able to search for any part of the large string. But that is probably a bit harder, I have to figure out how to do it myself. Never mind, will "Use The Force" :+)
ok but before i begin, what about the code? you said it was full of errors, whats wrong with it? I think i should delete whatever i dont need before i begin, that way when i start coding im not getting errors.
Well, I think your concept of the class is off a bit. An easy way to think of a class is that it holds some data (private member variables) and has functions that operate on that data. Some of them are public, like a get function, and any other public function that forms an interface (functions we can use to interact with the class). Others might be private: there is no need for the user to know they exist; but they might act as helper functions which a public function might call.

I think i should delete whatever i dont need before i begin, that way when i start coding im not getting errors.


Yes, unfortunately IMO I would delete all of it.

The problem is that you have the class with it's vector. But then you create functions outside of the class, which have new local vectors. Then you pass those local vectors to a class function, which overshadows (has the same name as, and gets used instead of) the vector the class already has.

Those functions should belong in the class, so you can use it's member vector.

I was supposed to write some code last night to help you a bit, by I was seriously distracted by a couple of other things. I will do another reply hopefully in the next 15 minutes with some pseudo code.
Ok, some pseudo code. As mentioned earlier, I recommend a std::map for now - it's easier. Later we could have a go with a regex, which will be much better, but harder to do.

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
// Create a class header file - call it ErrorMapper.hpp or ErrorLookup.hpp or something similar. Use your IDE 
// menu option so it creates the header file and a cpp at the same time
// class name exactly the same as the file name

// class definition in the header file

// Private member variables
// std::map<std::string, std::string> ErrorMap;
// remember to put the #include file for the std::map and std::string

// public functions
// there might be a way for your IDE to automatically make a function stub
// in the cpp file, using what you have here in the header file
// a default constructor no args
 
// function InsertInfo
void InsertInfo(const std::string& key,    // The short string to look up values 5 char long say
                     const std::string& value  // The actual value, the longer string
                    );
// not doing any implementation code here, that goes in the cpp file

// search for an error message with a short string key 
// return the long error as a string

std::string SearchErrorMsg(const std::string& key );




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
// in the cpp file create functions exact same as in the header file, with scope resolution
// if your IDE hasn't already done it:
// for example

 ErrorMapper::ErrorMapper() { //constructor

}

void InsertInfo(const std::string& key,    // The short string to look up values 5 char long say
                     const std::string& value  // The actual value, the longer string
                    )
{
// could either use operator[]
// http://www.cplusplus.com/reference/map/map/operator%5B%5D/
// look at the examples

// or std::map::insert
// http://www.cplusplus.com/reference/map/map/insert/ 
}


std::string ErrorMapper::SearchErrorMsg(const std::string& key ) {
// could either use operator[] again

// or use std::map::find
// http://www.cplusplus.com/reference/map/map/find/
// look at the examples
}





1
2
3
4
5
6
7
8
9
10
11
12
13
// main.cpp
// include files

// create an instance of your map
// repeatedly call the function to put info in

// use the operator[] directly
// The string in the [] must be unique for the whole map

MyErrorMap["Jag"] = "Danger: Jaguar Thralls about\n"
MyErrorMap[ "Door"] = "Door Locked, need to take care of other things first\n"

// call the function to search for a value. It returns a string so what are 2 ways you could use that? 


See how you go with that :+)
Topic archived. No new replies allowed.