Bench 212 Posting Pro

Here, you have declared a variable called ptr

void question1()
{
int i=0;
int* ptr=nullptr;

Here you are declaring a completely different variable, which also happens to be called ptr and hides the variable you'd previously declared by the same name.

while(boolean!=false)
	{
		cout << "Enter number: " << endl;
		int* ptr=new int[i+1];

Since this new ptr variable is declared inside your loop, it is destroyed at the end of your loop, and the new int[] memory which you'd allocated is being leaked, since there are no other references to it in your program.

I'd suggest renaming one of your 'ptr' variables, and being careful to ensure that the memory you're allocating is properly tracked, and also deleted when you no longer needed. (Note, memory allocated using new[] needs to be cleaned up with delete[] - don't omit the subscript [] operator)


Alternatively, a smarter way to do this (without new/delete) would be to avoid yucky stuff like pointers and new/delete, then to replace it with a vector (which is a resizable "C++ array")

#include <vector>
// ... etc.
vector<int> temp;
bool boolean=true;
while(boolean!=false)
{
    cout << "Enter number: " << endl;
    int n;
    cin >> n;
    if(n!=-1)
    {
        temp.push_back(n);
    }
    else
    {
        for(int j = temp.size() -1 ; j>=0; j--)
        {
            cout << temp[j] << " " ;
        }
        boolean = false;
    }
}
Bench 212 Posting Pro

Please provide more detail; Does your program compile successfully?
If not, then please post the compiler errors/warnings;
If so, what happens when you run your program, and how does this differ to what you're expecting?

Bench 212 Posting Pro

This thread is missing the most important step IMO.

Software development always starts out with the statement of a problem; that is to say that Programming IS problem solving. With this in mind, you cannot expect to design a solution without first defining, in detail, what exactly you're trying to solve.

Most people can usually visualise a small/medium problem, but anything complicated needs more thought; the thought process might go as follows:

  • Define the problem
  • Define the requirements of a solution (i.e. What tasks/activities do you want to be able to perform?)
  • Evaluate each of the requirements
  • begin to define the specifics (i.e think about what the solution should actually do)
  • Create one or more prototypes as necessary for various bits of functionality - this in itself will often unearth sub-problems which you hadn't previously considered

Not all of those steps will necessarily occur; and if they do, they do not have to occur in any specific order (except for the step where you initially define the problem). The key point to note is that unless you understand at least part of the problem, you have little hope of being able to create a solution.

Just as an example, think about a web browser

The problem: Unable to browse the web

The requirements (Why i want to browse the web and how i want to browse it):
- Specify an URL containing an HTML document
- Connect to the URL …

Bench 212 Posting Pro

I hate to be a bore, but Narue has written an extremely concise, in-depth post which is pinned at the top of this forum called How do I flush the input stream? - Please pay attention to sticky threads in future :-)

http://www.daniweb.com/forums/thread90228.html

Bench 212 Posting Pro

I didn't compile your program bench, but in some compiler you may need to use the
keyword, typename in your to_string function, specifically here

typedef std::iterator_traits<FwdIt>::value_type value_type

Well spotted - VS2008 didn't pick up on that even after I switched off MS-specific extensions, however if I use the same typedef in a class/struct, then it correctly throws out an error. I guess I should rely on the comeau compiler more often!

Bench 212 Posting Pro

I believe you may be somewhat re-inventing the wheel here - you can achieve the same result using a std::stringstream, an ostream_iterator and the std::copy algorithm :-)

#include <string>
#include <algorithm>
#include <iterator>
#include <sstream>

template<typename FwdIt>
std::string to_string(FwdIt begin, FwdIt end)
{
    //retrieve the value type for any kind of iterator, including a "raw" pointer
    typedef std::iterator_traits<FwdIt>::value_type value_type;

    std::ostringstream buffer;
    std::ostream_iterator<value_type> buffer_inserter(buffer, " ");
    std::copy(begin, end, buffer_inserter);
    return buffer.str();
}

main/test:

#include <iostream>
#include <vector>

template<typename T, int N> 
T* end_of(T (&arr)[N])
{ return arr+N; }

int main()
{
    double foo[] = { 10.1, 20.2, 30.3, 40.4, 50.5 };
    std::vector<double> bar(foo, end_of(foo));
    std::cout << to_string(bar.begin(), bar.end());
}
StuXYZ commented: good example +3
Bench 212 Posting Pro

I find the argument about simplicity to be somewhat perplexing - C++ and Java have amazingly simple syntax rules when compared to any natural language.

I reckon you could summarise the fundamental syntax of most programming languages using a handful of sheets of paper; on the other hand, natural languages are enormously complicated - linguistics experts fill entire books documenting the structure of languages such as English - the number of varying factors of words in a natural language is vast.

e.g. consider the changing meaning of these words simply by fiddling with punctuation

"Clive bent over because the book had fallen on the floor to the left of the shelf..."
"Clive, bent over because the book had fallen; on the floor, to the left of the shelf..."
"Clive, bent over, because the book had fallen on the floor, to the left of the shelf..."
"Clive bent over; because the book had fallen on the floor, to the left of the shelf..."

All of those sentences are 'technically' gramatically sound (either on their own or as part of another sentence), but please do try explaining the difference to a non-english speaking human letalone a computer :-)


Perhaps what you mean is that you are more familiar with English than you are with Java or C++, and you also probably aren't too familiar with how computers "think" either - but thats because you probably spent your entire life learning and English, …

jonsca commented: Nice arguments +4
Bench 212 Posting Pro

what exactly is REGISTER_BUILDER? are you 100% sure that its a function? usually ALL_UPPERCASE names are reserved exclusively for #define macros

it would help a great deal if you could show us the definition of REGISTER_BUILDER.

Bench 212 Posting Pro

Tell your school that you are unhappy about being taught using obsolete technology. Turbo C++ has no place in today's world, and insist that they provide you with an education which is relevent - i.e. by teaching you using modern material which works on modern compilers.

Bench 212 Posting Pro

Construction order has nothing to do with the compiler

Sorry, that's poorly worded; what I meant was "object construction doesn't happen at compile time".

Bench 212 Posting Pro

Well the main problem with starting the construction of a class from the derived part up to the base is that any variables you are using that are in your base in a function in your derived class would be undefined. Assume this situation.

class A
{
    int number;
};

class B : public A
{
    void foo() { number++; }
};

In this situation the compiler would have no idea what number is when it tried to compile it if it were to start at B and go to A. Since it goes the other way there is no problem.

Construction order has nothing to do with the compiler - object initialisation happens at run time. Also, your code still has problems in that number is undefined by the base class irrespective of the order that the classes are constructed.
And lastly, foo is not a constructor, nor is it called by any constructors so is not involved in the construction order anyway.

A better example to illustrate construction order might be this

class A
{
    int number;
public:
    A(int n) : number(n) {}
    void display()
    {
        std::cout << number;
    }
};

class B : public A
{
public:
    B(int n) : A(n) 
    {
        display();
    }
};

If the rule were that B must be fully constructed before creation of A can commence, then the constructor for B would have had to finish before A(n) is called - however, display() relies on A::number being well defined.

Bench 212 Posting Pro

I don't really see how knowing "why" actually helps, although if you think about what inheritance represents, it should be obvious - a base class represents generalised components which are common to all objects in a heirarchy - essentially a base class is a 'sub set' of its derived classes - it makes sense that the common subset is created first before the specialisations.

Bench 212 Posting Pro

I am curious, but wouldn't this allow *any* class that happens to allocate the same amount of memory as Small?

No, That's not how it works - there are two overloaded functions which are used to determine the convertability.

small test(base&);
big test(...);

the class checks the sizeof the return types of these functions. the sizeof the return type will only be 'small' when the class is convertable to base&, otherwise, the type will fall into the ellipsis.


This isn't in any way circumventing the language constructs - its completely portable, and works on well-defined behaviour of the ellipsis operator ...

Bench 212 Posting Pro

Andrei Alexandrescu came up with a way to check convertability between types at compile time as part of his Loki library
http://loki-lib.sourceforge.net/

- you could use a similar trick to enforce the types which are allowed to use your container

class base {};
class derived : public base {};


template<typename T, typename Base>
class relationship 
{
    typedef char Small;
    class Big { char dummy[2]; };
    static Small Test(const Base&);
    static Big Test(...);
    static T MakeT();
public:
    enum { exists = 
        sizeof(Test(MakeT())) == sizeof(Small) };
};

template<bool> struct check;
template<> struct check<true> {};


template<typename T>
class container : public check<relationship<T, base>::exists>
{
};

int main()
{
    container<derived> cd;
    container<base> cb;
}
Bench 212 Posting Pro

if the base class were responsible for cleaning up memory within its destructor, then stopping that code being called would of course cause a memory leak.

I can't see how that could benefit you, unless you have some reason why you'd intentionally not want that memory to be released - if this is the case, then you should think about changing the design of your program (move the responsibility for that memory block elsewhere) - or create a copy before that memory is cleaned up.

Whatever code you wish to prevent being run in your base class destructor, you might think about moving it out of that destructor, or perhaps setting a flag which dictates whether or not some or all of that destructor is used

class base
{
    const bool cleanup;
public:
    base() : cleanup(true) {}
    base(bool b) : cleanup(b) {}
    ~base()
    {
        if(cleanup)
        {
            std::cout << "base destructor" << std::endl;
        }
    }
};

class foo : public base
{
public:
    foo() : base(false) {}
    ~foo()
    {
        std::cout << "foo destructor" << std::endl;
    }
};

class bar : public base
{
public:
    ~bar()
    {
        std::cout << "bar destructor" << std::endl;
    }
};

int main()
{
    foo f;
    bar b;
}
Bench 212 Posting Pro

Here I know what exactly happened, and I want to show this message to the user

This is your major problem - exceptions should not be used for handling user errors, and users shouldn't need to know about exceptions which have occurred in your program - That is to say, if the user does need to know about it, then its not really an exception.

If you know exactly what happened, then you can deal with it in some other way. Exceptions are generally used for handling mistakes which you or another programmer might make when using your code - where those mistakes affect the inner workings of something else; for example, passing invalid data to a constructor or running an iterator or loop beyond the boundaries of a container. - situations where the best solution to a problem is to throw the error back to the calling code, and let that code clean up any mess which may have been left over.

You may be approaching C++ exceptions with a Java mindset, where exceptions are often used to handle all kinds of things (obviously, C++ is not Java). In C++ you should only use exceptions to handle circumstances which are truly exceptional - user interaction really isn't one of those things, since you should always be expecting that a user is likely type in something wrong, and don't really need to throw errors back to calling code.

Most of the time validation which can decay into …

Bench 212 Posting Pro

a statically allocated array is "statically allocated" because its size is known by the compiler (its size is static - static means that it can't and won't change)

The compiler will ensure that a statically allocated array is created with a fixed size.

However, the compiler has absolutely no control over anything which is not known at compile time; this includes concepts such as memory addresses and user input, therefore there is no such thing as a statically allocated array whose size is known at runtime - its a pure contradiction


if you wish to create an array at runtime, then the compiler doesn't know how much space you need, therefore you must manually allocate and clean up memory yourself, or use a container which will handle memory at runtime (And is free to shuffle data around in memory for you, so maintaining pointers to elements stored in a container is undefined behaviour).

Perhaps you could shed some light on exactly what you're trying to do in 'real' terms? i.e. what problem are you trying to solve?

Bench 212 Posting Pro

That would be a contradiction in terms; an array whose size is decided at runtime is a dynamic array.

If you mean you'd like a dynamic array where you don't need to worry about explicit memory management, then the STL vector is C++'s "dynamic array".

edit: But having seen what you're trying to do, that would cause more problems than it would solve.
Why are you trying to use a map to delete some objects which that map is not responsible for? The obvious solution would be to redesign your program so that the map itself is responsible for the objects, not the array.

I come before you, to stand behind you,
To tell you something I know nothing about.
Next Thursday, which is Good Friday,
There will be a mothers' meeting for fathers only.

Bench 212 Posting Pro

The problem is in your Add function - When you read anything using cin >> , there'll be (at least) a newline character left over from when the user hit 'enter';

using cin.ignore() will discard one character, but if the user typed in any other junk, you might sometimes need to discard more; a better way to do that would be to tell cin.ignore to ignore everything

#include <limits>
std::cin >> x;
std::cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
Bench 212 Posting Pro

What the OP wants to do is called downcasting. It's not recommended for the obvious reasons, but it's a feature that C++ supports using dynamic_cast because it's sometimes necessary:

Yes, but the example shown in the OP was attempting to access a Base object via a Derived pointer

PersonClass* Person = new PersonClass;
LawyerClass* Lawyer = static_cast<LawyerClass*>(Person);

Unless I've misread the OP's intentions their goal is to change the type of the object itself at runtime (i.e. they want to extend it to become a valid LawyerClass object instead of PersonClass); Since that most likely means extending the size of the PersonClass object, I can't see any way that could be done safely without creating a new LawyerClass object elsewhere.

Bench 212 Posting Pro

Think about the relationship described by inheritance, and why what you're doing isn't possible;

class Vehicle {};

class Bike : public Vehicle {};
class Car : public Vehicle {};
class Truck : public Vehicle {};

The relationship can be described as "IS A"; in other words, Car IS A Vehicle and Truck IS A Vehicle. But the reverse is not true - Vehicle is not a Truck, and Vehicle is not a Car; Vehicle is just a Vehicle.

A Vehicle could be used as a starting point to create a Truck, Car or Bike, maybe, since a Vehicle contains some of the information about those derived classes, but that information is incomplete. You can't change the type of an object, so you will need to create a new one instead, using the Vehicle object as the derived object's constructor information

class Vehicle {};

class Bike : public Vehicle 
{
public:
    Bike(const Vehicle& v) : Vehicle(v) {}
};
class Car : public Vehicle
{
public:
    Car(const Vehicle& v) : Vehicle(v) {}
};
class Truck : public Vehicle
{
public:
    Truck(const Vehicle& v) : Vehicle(v) {}
};
Bench 212 Posting Pro

hey, everyone. I am still learning templtes and I have 2 questions:
1-Why is it that all the examples of templates I have seen are about arrays?Is that all templates are used for?

I suppose because containers are the most prominent and easy-to-explain examples when it comes to introducing templates - its probably safe to say that you'll encounter a vector very early on in your C++ learning, and a vector is a great example of an application of templates.
Beyond that, templates can be (*ab)used for some immensely complicated, mind-bending solutions to address some very large and difficult problems.

* = Some would argue that templates were intended to be simple, but the true C++ Guru's in the world discovered that templates were actually capable of almost standing alone as an entirely new turing-complete programming language, albeit one which is incredibly ugly and sometimes hard to understand, but extremely powerful nonetheless.

2-after pondering about the above question, I decided to try something else witha template..a generic unction.
However the program just hangs when I run it. Only one object is created(because I always put a sentence in my constructors, to know when an object is created. the sentence appears only once.)
Can someone help me out? Thanks in advance!!

T dat1,dat2;
 display():dat1(0),dat2(0){

Your initialiser list assumes that dat1 and dat2 are capable of taking 0 as their constructor argument - but for std::string, this will actually do something really dangerous (that zero converts …

Bench 212 Posting Pro

Is it an unsound supposition or a mild form of deliberate insult?
Have you ever seen my home library?

No offense nor insults intended at all. I merely assumed from your post that you had not read some of the highly acclaimed books from the likes of Sutter, Meyers, Alexandrescu, etc. If i'm mistaken, then ignore my response - though I'd still be curious to know why you believe TCPPPL is the only good C++ book (Unless i've missed some hidden sarcasm or irony, in which case ignore this) - if you've read any books by the authors I've named here, you'd surely be aware of their standing among the C++ community.

Bench 212 Posting Pro

I have no comments. I think the only good book on C++ is "The C++ Programming Language" by B.Stroustrup ;)...

Even Stroustrup himself wouldn't say that. There are many really excellent C++ books floating around (of which TCPPPL is just one). If the only book you've ever read on C++ is that one, then you're missing out on a wealth of information.

Bench 212 Posting Pro

In the latest code you posted, you're using the case keyword after an if statement. case is intended to be used in conjunction with switch, and is meaningless on its own.

Perhaps you could also show the declaration of your tfgame object, and the declaration for ToggleWarhead

Bench 212 Posting Pro

can the name possibly be a number or something, it has to be something that I can increment by 1 or something before I make another atom object, and yes I have used pointers like once or twice but havent found too much use for them yet in my programming, maybe now is the time :)

so basically everytime I create an atom object its name has to be slightly different to differentiate between all the atoms created in the simulator.

Why do they need to have names at all? isn't it simply enough to be able to store un-named atoms in a vector and be able to find them using their position/index within the vector?
The "names" which you see when you're writing your code are for your convenience only - when you send your program through the compiler, those names become non-existant, because your computer doesn't need them - it remembers objects by their 'index' (address) in your computer's memory instead.

Bench 212 Posting Pro

Noone will spoonfeed you any solutions. have a good attempt at the problem for yourself and come back if you get stuck on anything along with a description of whatever it is you need help with, and the code you've tried so far.

Bench 212 Posting Pro

It sounds as if you need to set up some accessor/modifier methods within your account class, rather than attempting to access them directly from your bank member functions. private data members of a class can only be directly accessed from other members of that same class

Bench 212 Posting Pro

You mentioned that you attempted a return type of Tree<T>::Node , However, that's not sufficient for the compiler to take your word for it that Node is indeed a type identifier and not something else.

The issue is that Tree<T> is an incomplete type, where Tree::Node could be absolutely anything depending on the specialisation of Tree<T>

The solution is to use the typename keyword to give the compiler the extra hint that Tree<T>::Node is indeed a type

template<class T>
class Tree {
    struct Node { int a, b; };
    Node createNode();
    T b;
};


template<class T>
typename Tree<T>::Node Tree<T>::createNode() {
    std::cout<<"how are you\n";
    Node n; n.a=n.b=10;
    return n;
}
Bench 212 Posting Pro

Why don't you try it for yourself and find out? If the compiler doesn't complain, then you know its ok

The only point where your compiler might produce an error, is if you attempt to compile under C++, where true and false are reserved words which cannot be reused elsewhere. This shouldn't be an issue under C

Bench 212 Posting Pro

Additional:

It seems I was half-right, although, the STL uses the std::less<T> functor class as its default predicate for sorted containers, as found in the <functional> header. (std::less in turn assumes that operator< is available)

The STL also takes the extra step of enforcing the predicate to match a certain type (Which the example I gave doesn't do), using an additional template parameter, which defaults to std::less<T>. This is presumably a safety net to stop predicates for different types being used accidentally.

Bench 212 Posting Pro

I could be mistaken, though I believe that the STL sorted containers expect a type with a valid operator<. If the type doesn't provide one, then overloaded constructor(s) will take an additional parameter in the form of a compare function, or a function object which overloads operator() instead.

Since you don't know the precise type of the comparator in advance, you need to provide a templated constructor where any kind of comparator can be used to compare objects within the data structure


Here's a brief example of a constructor accepting a functor, whose type is determined at compile time.

/* less_comparator - user-defined comparison */
template <typename T>
struct less_comparator
{
    bool operator()(T, T) const;
};

template <typename T>
bool less_comparator<T>::operator() (T lhs, T rhs) const
{
    return lhs < rhs;
}

template<typename T>
class structure
{
public:
    structure() {}
    template<class Comparator>
    structure( Comparator comp )
    {
    }
};

int main()
{
    structure<int> s( less_comparator<int> );
}
Bench 212 Posting Pro

at this line pizza.set ( x , y , a[7] , i ) ;

a[7] is an element in your array
(Also - if your array is only 7 elements in size, then valid elements are indexed 0-6, so you're accessing one-past-the-end.)

try this instead pizza.set ( x , y , a, i ) ;

Duki commented: thanks for the help +4
Dave Sinkula commented: Thanks. I had made that change but forgot to post it. +11
Bench 212 Posting Pro

the problem might be easier for you to see if you used a more consistant indenting style.

Here it is, reformatted (Courtesy of MSVC++'s auto-format tool):

int main() 
{
    clrscr();
    int one, two, three,x;
    char choice;
    while (choice != 'e')
    {
        cout<<"\nWELCOME! To access my calculator, please follow the instructions carefully.";
        cout<<"\n\n\n";
        cout<<"\nPlease enter the correct number code: ";
        cin>>x;
        if (x!=123)
        {
            cout<<"\n";
        }
        else
        {
            cout<<"\nYou may now use the calculator!";
            break;
        }
    }

    cout<<"\nPlease enter +,-,*, or / and then two numbers,\nsepperated by spaces, that you wish to\nadd,subtract,multiply,or divide.\n\nType e and press enter to exit.";
    cin>>choice;
    if (choice != 'e')
    {
        calc(choice);
    }
}

your if (choice != 'e') statement is not inside any kind of loop, so there is nothing to make it repeat.


I'd also like to point out this bit

char choice;
    while (choice != 'e')

your 'choice' variable is uninitialised when you compare it for inequality with 'e', which causes undefined behaviour (anything can happen...)

Bench 212 Posting Pro

Of course some professionals use goto's occasionally ... with reference to the linux kernel, here's Linus Torvalds' take on goto

http://kerneltrap.org/node/553/2131


Although I would put goto's in the same league as Macros, Unions, Multiple Inheritance, reinterpret_cast, placement new ....

in other words - all things which you should generally avoid unless you really, totally understand what you're doing, where the pitfalls are, and what the alternatives are (And have made a concious decision that the benefits of your chosen technique outweighs the potential problems)

Bench 212 Posting Pro

I ran your code, Bench, but it doesn't do what gaggu82 asked for. It finds the search string even if it's embedded in another word, like "this is a string" prints "is is a string" instead of "is a string". Am I testing it the wrong way?

No, you're not :) I think the original post was unclear to me (It makes more sense now - the thread starter could have done with more punctuation though - the question was bordering on cryptic as I read it)

in which case, i'd add this to the top

bool is_space_punct( std::string::const_iterator iter )
{
    return isspace( *iter ) || ispunct( *iter ) ;
}

and use this for bounds checking (I don't think the STL can help much with this bit)

bool is_word = true;
    if (iter != line_in.begin() )  //Don't check the beginning
        is_word = is_space_punct( iter-1 );

    if ( iter+match.size() != line_in.end() ) //Don't check the end
        is_word = is_word && is_space_punct( iter+match.size() );

Now its fairly similar to yours, but with iterators rather than indices (I tend to find iterators are a bit more idiomatic for C++, probably because of the huge number of things you can do with the STL algorithms) :)

Bench 212 Posting Pro

There might be a way in the STL to do it, but I don't know. I'd write a search function that finds every occurrence of "is" and then checks to see if the first and last letters are on a word boundary.

Yep, the STL is handy here, although your way works fine too.

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
    const std::string line_in("the cat sat on the mat");
    const std::string match("cat");
    std::string::const_iterator iter =
        std::search(
            line_in.begin(), 
            line_in.end(), 
            match.begin(), 
            match.end() 
    );

    if (iter != line_in.end() )
        std::cout << std::string(iter, line_in.end() ) << std::endl;
}
Bench 212 Posting Pro

you don't need to take value_type out, just make sure the name is fully qualified when using it outside of the class, ie,

[b]node::[/b]value_type node::get_data() const
Bench 212 Posting Pro

Look at this section of code, where you ask the user to enter the number of children

void HowManyChildren(void)
{
	DailyChild=1.50;
	YearlyChild = 5.50;
	
	printf("\n");
	printf("#of Children:   ");
	scanf(" %d", &[B]childrenNum[/B]);
	printf("\n");

	if (childrenNum <= 999) 
	{
	}
	else 
	{
	printf("Invalid Number Entered, please try again.");
	printf("\n\n\n");
	HowManyChildren();
	}

	return;
}

After asking the user to input the number of children, your program doesn't do anything else with childrenNum aside from checking that its less than 999.

Somewhere you want to calculate the ticket cost using this number and your cost-per-ticket. Maybe you intended to put that in your ChildrenCalculations() function.

- With regards to C vs C++ - These days, its unusual for a C++ course to use things like printf, scanf, strcmp (They're valid in C++, but only for the sake of compatibility with C). Most modern C++ courses don't teach the language as 'a better C' - although there's nothing wrong with learning both languages, you'll find alot of things done differently when you move onto C++.

Bench 212 Posting Pro

This isn't C++ code, its C. (The two languages are very different)

Probably the reason that you get an error when your code exits, is that your declaration of main() is ill-formed.
Change your main declaration so that it looks like this -

int main(void)

As for your issue of the wrong output, it looks as if your program doesn't do anything with the number of children after you prompt the user for it.


I think your program has a lot of design issues - you're using alot of global variables, this is one way to make your program very messy and hard to follow. Try rearranging your program so that variables are declared where they're needed, and passed or returned to/from functions instead. You should find that the logic of the program is much easier to trace by doing this.

Bench 212 Posting Pro

First, look carefully at the compiler errors, and correct spelling/typing mistakes (I see at least one!)

Second, where is your struct definition..? (Perhaps you need to read up on how to create a struct)

Bench 212 Posting Pro

I think you missed the irony a little bit there... Salem posted a suggestion of putting the char into a string, then your reply contained "I got an idea..", where you went on to describe the same thing :)

I realise that might have been lost on some people ;)

Bench 212 Posting Pro

If you wanted to make the code smaller, you can use the C++ <string> library. (you have it at your disposal, so you may aswell use it..!)

#include <map>
#include <string>

typedef std::pair<std::string, std::string> entry_t;
typedef std::map<std::string, std::string> dictionary_t;

int main()
{
    const entry_t init[] =
    {
            entry_t( "dog", "four legged pet" ),
            entry_t( "fish", "swims in the sea"),
            entry_t( "clock", "tells the time"),
            entry_t( "radio", "plays music")
    };
    const int entries( sizeof(init) / sizeof(*init) );
    dictionary_t dictionary( init, init+entries );
}

As for the looping issue, the easiest way might be to perform a do...while( str != "EX" )

(the != comparator also only works when 'str' is a C++ string. this is another reason to ditch the char arrays)

Bench 212 Posting Pro

I suppose I should add that atoi() has no reliable way of handling any errors that might be thrown up when your conversion fails. This is where stringstreams provide a far more robust solution, that you can test for failure before using the retrieved value.

Bench 212 Posting Pro

Don't use atoi() - here's how to do it in C++

#include <sstream>
#include <iostream>

int main()
{
    const char* foo("1234");
    std::stringstream ss(foo);
    int i;
    if( ss >> i )
        std::cout << "i is: " << i ;
    else
        std::cout << "error";
}

The reason for using stringstreams is that your conversion will fail if the string contains anything which can't be converted to an int - which, if you're dealing with user input, is a real problem. if you use a stringstream, you can detect the error, without it messing up the rest of the program.

Killer_Typo commented: great post +6
Bench 212 Posting Pro

I tried that. However it only made things more difficult.

It split the contents of the file into individual lines therefore splitting up the information that I need.

Example.
>Name
ABCDEFG
HIJKLMNO

I have to extract the name, and then the letters must be stored together????

That's easy enough. Identify and isolate the vector elements which contain names, then concatenate the others together.

There's loads of different ways of doing this .. If this doesn't work for you, then you need to tell us how you intend to store the individual data 'records'. You may or may not be able to do it all in a single step.

Bench 212 Posting Pro

Just create a constructor in your DayOfYear class, which takes no parameters... just like you've done here

#include<iostream>
#include<conio.h>
using namespace std;
class DayOfYear
{
public:
[B]    DayOfYear(int month,int day);[/B]
    void output();
    void input();
private:
    int month_year;
    int day_year;
};
[B]DayOfYear::DayOfYear(int month,int day)
{
    month_year=month;
    day_year=day;
}[/B]
void DayOfYear::output()
{
    cout<<month_year<<"/"<<day_year;
}
void DayOfYear::input()
{
    cout<<"What's your month of birthday : ";
    cin>>month_year;
    cout<<"What's your day of birthday : ";
    cin>>day_year;
}
Bench 212 Posting Pro

You don't need to use switch at all, try the STL map container instead, where you can link strings to other strings (just like in a dictionary)

Salem commented: A map would be good, if the OP is that far into the course :) +9
Bench 212 Posting Pro

I could - but there's no guarantee that what happens when I try compiling & running it, is going to be the same as what happens when you try compiling & running it (Especially not when you've missed out CODE tags, and your code has got forum icons in it... )

The error you're getting is because the compiler can't find a default constructor in the DayOfYear class.

When you write your own constructor, the default constructor is no longer available automatically, so you either have to make one, or change your code in main, so that its using the constructor you've already written..

DayOfYear bach_birthday(3,21),my_birthday;
Bench 212 Posting Pro

Why are you copying the file contents out of a filestream, into a stringstream, then, into a string, and then, into another string?

you can extract each line of the file one by one straight into your vector, without all that fuss...

#include <iostream>
#include <vector>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream fs("test.txt");
    string input;
    vector<string> sets;
    while( getline(fs, input) )
        sets.push_back(input);
}

All which remains is to work out which elements in your vector are names (the ones which start with '<' )