views:

633

answers:

2

I've been given a homework assignment to write a program in C++, but we're not allowed to use the string class. However, we are allowed to use the iostream library, including stringstream. I was thinking of using stringstream where I would have used string for building my classes, returning from functions, etc.

Does this sound like a good idea to you? Any pitfalls I should be aware of?

+9  A: 

You could also use vector<char>. It's a good alternative to string. As Scott Meyers says in his "Effective STL" book:

Third, consider using a vector<char> instead of a string, vector implementations are not allowed to be reference counted, so hidden multithreading performance issues fail to arise. Of course, you forgo string's fancy member functions if you switch to vector<char>, but most of that functionality is available through STL algorithms anyway, so you're-not so much giving up functionality as you are trading one syntax for another.

I think the main problems that could arise from using stringstream are that it's not strictly a container. I'm not sure if it is possible to use algorithms and other regular STL stuff with streams.

A: 

If the situation is a shop database without strings, you could just simply use an enum.

enum {
     Prod1,
     Prod2,
     Prod3
};

Which means you can just pass integers around as identifiers and then just have a print function with a switch statement.

void PrintProd(int product) {
    switch(product) {
         case Prod1: 
              cout << "Product 1" << endl;
              break;
         case Prod2:
              cout << "Product 2" << endl;
              break;
     // etc.
     }
}

This allows you to bypass a lot of trouble. If you don't mind dealing with the heap, a vector of char* allocating the product names with the id's being the index into the vector would work too.

Zeroshade