# FBi's running C++ questions



## [I.R.A]_FBi (May 28, 2008)

Clearscreen with anything else other than clrscr

Anyone can help me


----------



## [I.R.A]_FBi (May 28, 2008)

need to

#include <stdlib.h>

system("cls");


----------



## [I.R.A]_FBi (May 28, 2008)

how do i make the screen pause for 5 seconds?


----------



## [I.R.A]_FBi (May 28, 2008)

//   windows.h needs to be included for this...

void DelaySecs(int secs)
{
     unsigned long int t=GetTickCount()+(1000L*secs);
   while(GetTickCount()<t)
   {      /*  Wait !!!*/    }
}


----------



## Kreij (May 28, 2008)

You can also get a lot more flexibility with clearing the screen if you write your own little routine.

Basically you just need to write spaces to the screen buffer where you want to clear it.

You accomplish this by making a call to the FillConsoleOutputCharacter() function.
The function takes 5 arguments, like so..

```
BOOL FillConsoleOutputCharacter(
    HANDLE hConsoleOutput,                // screen buffer handle
    TCHAR  thisChar,                     // character to fill the screen with
    DWORD thisLength,                    // length to fill with character
    COORD startCoord,                    // starting coordinant
    LPDWORD numWritten                    // number of characters written
};
```

So let's say that you want to clear the screen, but not the first line which is a title.


```
#include "stdafx.h"
#include "windows.h"

void ClrScreen()
{
    HANDLE hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD myCoord = { 0, 1 };  // Keep first line intact, use 0,0 to erase whole screen
    DWORD numWritten;  // We are just ignoring this as we don't care

    CONSOLE_SCREEN_BUFFER_INFO sbInfo; // To get screen buffer size
    GetConsoleScreenBufferInfo(hStdOutput, &sbInfo);

    FillConsoleOuputCharacter(hStdOuput, ' ',
        (sbInfo.dwSize.X - myCoord.X) * (sbInfo.dwSize.Y - myCoord.Y,
        myCoord, &numWritten);

    SetConsoleCursorPosition(hStdOutput, myCoord);   // Position the cursor
}

int main(array<System::String ^> ^args)
{
    Console::WriteLine("Kreijs Program Title");
    Console::Write("Press any key to clear screen but keep title : ");
    Console::ReadKey();
    ClrScreen();
    Console::Write("Press any key to exit : ");
    Console::ReadKey();
    return 0;
}
```

As you can see, if you modify it a little and pass in the coordinants as variables, you could erase any portion of the screen buffer that you want. This could be used for simple animations and the like.


----------



## [I.R.A]_FBi (May 30, 2008)

god bless you.


----------



## Kreij (May 30, 2008)

[I.R.A]_FBi said:


> god bless you.



Thanks, that's very kind of you. 

I am not sure what exactly you are doing with the pause function, but you can give that a bit more flexibility by making it interruptable (if the situation calls for that capability).


```
#include "stdafx.h"
#include "windows.h"
#include "conio.h"

int PauseTimer (unsigned long SecsToPause)
{
	unsigned long StartTime = GetTickCount();
	SecsToPause *= 1000;

	while (! _kbhit())  // Loop if no key pressed, until time is up
	{
		if (GetTickCount() - StartTime >= SecsToPause) return 0;
	}
	return _getch(); // A key was pressed, return it's value
}

int main(array<System::String ^> ^args)
{
        Console::WriteLine("Program pausing ... hit any key to interrupt");
	switch (PauseTimer(5))  // Pause for 5 seconds or until interrupted
	{
	case 0 :
		Console::WriteLine("5 Seconds is up");
		break;
	default :
		Console::WriteLine("Interrupted by user");
		break;
	}
	Console::Write("Press any key to exit : ");
	Console::ReadKey();
	
             return 0;
}
```

Again, with a little modification to the PauseTimer() function, you could have it return the time it was actually paused instead of the key that was pressed.

Just another tip. If you don't need it, maybe one of the other lurkers here will find it useful.


----------



## [I.R.A]_FBi (Jun 3, 2008)

i needs more help .. im trying to do a menu based thing, so i wrong the code first and it ran ok, now i added the case and things get screwy ...

ima c++ n00b remember.

posting code shortly ...


----------



## [I.R.A]_FBi (Jun 3, 2008)

```
//  SOLUTION  
#include <iostream.h>  
#include <conio.h>  
#include <stdlib.h>  
#include <stdio.h>  

void customerMainMenu();

class customer 
{
      private:
              char fname[15];  
              char lname[15];  
              float  price, amtpaid, quantity,totalprice;   
         
      public :
             customer(); // no argument constructor
             void getCustomerDetails();  
             void buyItem();               
}; //  END OF  CLASS DECLARATION //FOR CUSTOMER = "DATA  //ABSTRACTION"

/*-----------------------------------------------------*/

// IMPLEMENTATION of  the functions  //for  the  CUSTOMER  OBJECT 
//:: // -represents the  scope  resolution  //operator, as used between the  function //name  and  the  object.  This  resolution  //operator  determines  what  object  has  //access  to  what  variables  within  a  //function   
customer::customer()
{   
    // Default  no  argument constructor
    ///This  means  variables are initialized to
    //their  default values
}    
    
void customer::getCustomerDetails() 
{
     // This  function  initializes  the customer  //record. This function  can  also  be  seen //as a  constructor  function  as  it  will  also  //initialize  the  variables  declared,  but  //dynamically  by  the  user.  This  type  of  //constructor  is  called  a "Primary default  //constructor" 
 
     cout<<"Enter the Customer's first name: ";  //This is where i have teh problem
     gets(fname);   
     cout<<"Enter the Customer's last name: ";  
     gets(lname); 
       
     // N.B  gets() allows a  user  to  read  a  //character  string  from  the  keyboard. This //function is  supported  by  the  stdio.h  //library  
} 

void customer::buyItem()
{
     cout<<"\nEnter the unit price: ";  
     cin>>price;   
     cout<<"Enter the quantity of items: ";  
     cin>>quantity;     
     cout<<"Enter the amount paid: ";  
     cin>>amtpaid;  
     
     totalprice =  price*quantity; 
       
     cout<<"\nPrice of the item is: "<<totalprice<<"\n";  
     cout<<"Amount paid by the customer is: " <<amtpaid<<"\n";   
}  //  end  of  buy  item  

/* 
Driver  function  to  test  the   
encapsulated  class  behaviour  of  
customer 
*/

int main()  
{ 
      customer k11; // k11 is a  //reference to  the  object  customer , or  //what  is  called  the  object  alias.    
  
      customerMainMenu(); 
      //k11.getCustomerDetails();  
      //k11.buyItem(); 

      getch(); 
      
      return 0;  
} //  end  main   

void customerMainMenu()
{
     int choice;
     customer k11;
               
     cout<<"..:: Customer Main Menu ::..\n";
     cout<<"\nWhat do you want to do?";
     cout<<"\n1: Enter Customer Details?";
     cout<<"\n2: Buy Item?";
     cout<<"\n3: Exit?\n";
     cout<<"\nEnter a choice: ";
     cin>>choice;
     
     while (choice != -1)
     {
           switch (choice)
           {      
                  case 1:    
                       k11.getCustomerDetails();                       
                       break;
                       
                  case 2:
                       k11.buyItem();                       
                       break;   
                                          
                  case 3:
                       system("cls");
                       cout<<"Have a nice day ...";
                       getch();
                        
                       exit(0);
                       
                  default:
                       cout<<"\nEnter a valid choice (1-3): ";
                       cin>>choice;
           }
           
           cout<<"Do you wish to do another transaction?: ";
           cin>>choice;
     }
}
```


when it comes to customer name input it skips the first name and goes right to the 2nd


----------



## Oliver_FF (Jun 3, 2008)

Ok these kind of bugs are rather obscure, but it relates to your use of cin and gets...


```
int a;
cin << a;
```

If you take that code, run it, then press these keys: 1 -> 2 -> \13[enter]
The enter breaks the input and reads the number 12 into a. \13 remains on the input.
Next up, it does a gets() which reads the standard input until it finds the newline character, \13... Well that's still there from the previous bit of text entry, so it has that. Then it moves to the next one. gets() is also a function to be avoided because you can't specify maximum length of characters to read, so it's a top target for buffer overflow attacks.


The better and safer way of doing console IO is to use printf() and scanf():

*printf*
http://www.cplusplus.com/reference/clibrary/cstdio/printf.html

```
int a, b, c;
String s1, s2;
printf("String: %s, %i -- %i; %s +-+ %i", s1, a, b, s2, c);
```
might produce:

```
String: bob, 5 -- 6; test +-+ 5
```
printf() takes an intial parameter as a string. This string specifies the formatting of your output. This formatting string is printed to the output, replacing all %i's, %s's etc with the remaining parameters to the function. In the example, it prints "String: " then there's a %s which means the second paramater to the fuction is a string, and we want that next. Then it prints ", ", then the third parameter which we've said is an integer... etc


*scanf*
http://www.cplusplus.com/reference/clibrary/cstdio/scanf.html
scanf does exactly the same as printf only in the opposite direction, it'll read from the console input matching against the pattern you give it, then set the values to what you entered.

```
int a, b, c;
String s1, s2;
scanf("String: %s, %i -- %i; %s +-+ %i", s1, a, b, s2, c);
```
If you type into the console "String: bob, 5 -- 6; test +-+ 5" then it will result with:

```
a = 5
b = 6
c = 5
s1 = bob
s2 = test
```


----------



## [I.R.A]_FBi (Jun 3, 2008)

thanks, it helped.


----------



## Oliver_FF (Jun 3, 2008)

If you are working with gcc, you should add the compiler option "-Wall" which means show all the warnings your code generates - you might get a shocking number of warnings, but they're a lot better than a mystifying bug later on


----------



## Deleted member 3 (Jun 3, 2008)

[I.R.A]_FBi said:


> need to
> 
> #include <stdlib.h>
> 
> system("cls");



That's dirty, using external commands.


----------



## [I.R.A]_FBi (Jun 3, 2008)

whats a good free compiler, currently uing dev cpp


----------



## [I.R.A]_FBi (Jun 3, 2008)

DanTheBanjoman said:


> That's dirty, using external commands.



versus?

im here to learn.


----------



## [I.R.A]_FBi (Jun 3, 2008)

Oliver_FF said:


> If you are working with gcc, you should add the compiler option "-Wall" which means show all the warnings your code generates - you might get a shocking number of warnings, but they're a lot better than a mystifying bug later on



Im using Dev c++ by bloodshed.net, it givess warnings.


----------



## Deleted member 3 (Jun 3, 2008)

Why don't you just use clrscr()? And why are you working in a console window anyway?


----------



## [I.R.A]_FBi (Jun 3, 2008)

DanTheBanjoman said:


> Why don't you just use clrscr()? And why are you working in a console window anyway?



cause my compiler doesnt recognize it. Reccomend me one please!


----------



## Deleted member 3 (Jun 3, 2008)

[I.R.A]_FBi said:


> cause my compiler doesnt recognize it. Reccomend me one please!



Conio.h


----------



## Kreij (Jun 3, 2008)

[I.R.A]_FBi said:


> whats a good free compiler, currently uing dev cpp



You could use C++ Express from Microsoft. It's free and has a full IDE (Visual Studio).


----------



## [I.R.A]_FBi (Jun 3, 2008)

It was included but it still says "clrscr undeclared, first use of function"


----------



## [I.R.A]_FBi (Jun 3, 2008)

Kreij said:


> You could use C++ Express from Microsoft. It's free and has a full IDE (Visual Studio).



ok.


----------



## Deleted member 3 (Jun 3, 2008)

[I.R.A]_FBi said:


> It was included but it still says "clrscr undeclared, first use of function"



Code?


----------



## Kreij (Jun 3, 2008)

From the Dev c++ FAQ ...


> *`clrscr' undeclared (first use this function)
> [Linker error] undefined reference to `clrscr'
> Why can't I use conio.h functions like clrscr, gotoxy etc?*
> First you should note that conio.h is a Borland extension, NOT a standard header, so Dev-C++ and MinGW are in no way required to support it. The MinGW included with Dev-C++ 4.9.9.1 comes with a very reduced version of conio.h (no clrscr, gotoxy, etc); if you need more then you can use the native Windows console functions.
> I also provide and maintain an updated version of conio (and also winbgim) at http://www14.brinkster.com/aditsu/console/; that may be what you are looking for.


----------



## Deleted member 3 (Jun 3, 2008)

What a *censored*s. In older versions of dev cpp clrscr() worked fine. I was forced to use it at school years ago.

So, back to the previous question, why a console window?


----------



## [I.R.A]_FBi (Jun 3, 2008)

its all i know


----------



## Oliver_FF (Jun 3, 2008)

To be fair, creating anything non-console based without using Visual Studio is a real nightmare.

I too use Dev-C++ for both my C and C++ apps - it's pretty sweet in that it's free, easy to use and lightweight.

As for clearing the screen, generally no application clears the window because the entire point of it is that you can go back and see what you did. Most programs actually just bump you down a few lines so it LOOKS like you've got a clean screen, but you're in essence just 3 lines down the page...

If your working with Unix you can you the curses library to do neat things with the command line, like ASCII animations, loading bars and crazy stuff like that. Sadly MS aren't big on the command line thing, and GCC is built for Linux so you get a big mugged over with the command line on Windows


----------



## [I.R.A]_FBi (Jun 3, 2008)

Oliver_FF said:


> *To be fair, creating anything non-console based without using Visual Studio is a real nightmare.*
> 
> I too use Dev-C++ for both my C and C++ apps - it's pretty sweet in that it's free, easy to use and lightweight.
> 
> ...



It was easier with VC++6, a little bit .. i may have to look for it again.

by non-console im assuming you mean "the dos window"


----------



## Kreij (Jun 3, 2008)

non-console means using a GUI instead of the "dos window".

All of the VS2008 Express editions make it very simple to write GUIs.
It generates all the code for all the windows and controls (like buttons, etc.) for you.

It's nice, becuase you can then look at the code that VS generates to learn how certain things are done. 

I will admit, however, that on occasion VS generates a ton of code for what could be very simple things.


----------



## Oliver_FF (Jun 3, 2008)

non-console i'm meaning like some kind of GUI - you know when you see this free software floating around with grey windows, buttons and text boxes?

Yeah - the console, in windows, is "the dos window"...

Visual C++ supports a GUI builder and plenty of stuff for the command line - it's a free download too atm. Well, Visual C++ Express Edition is. http://www.microsoft.com/express/vc/


----------



## [I.R.A]_FBi (Jun 3, 2008)

I had it installed already but it was a bit intimidating, so i went to dev


----------



## Kreij (Jun 4, 2008)

Okay, IRA, if you want to get over your "fear factor" of VS, try it again and post anything that you are not sure of and we will guide you along.

I am not saying that one is better than the other, but VS really makes it easier for a beginner to jump in and get results, even if they don't understand everything.

MS has done a very nice job of combining a fully functional IDE (Integrated Development Environment) with a RAD (Rapid Application Development) environment for developers.

If I were you, I would download C# express and start there. It is more intuitive than C++ for someone who is trying to learn the basics. You can always return too C++ if you want, once you know the basics.

I don't wish to sound like a MS fanboi, but you really cannot find an IDE that integrates all of the programming languages into a seamless development environment. You can easily code in whatever language you want, and they will work together because of the nature of the .Net framework.

I hold MS in contempt for some of the things they have done, but releasing their entire coding environment and all their compilers for free is not one of their bad moves.


----------



## CrAsHnBuRnXp (Jun 4, 2008)

Code makes me cry.


----------



## Kreij (Jun 4, 2008)

CrAsHnBuRnXp said:


> Code makes me cry.



How does your comment in any way add to this thread?
Unless you are crying out for coding help. In which case we will be happy to assist you.


----------



## CrAsHnBuRnXp (Jun 4, 2008)

It doesnt really.

I can add that it doesnt make a lick of sense to me. I bought a book about a year ago and tried reading up on it. It just doesnt click in my head. 

And when your getting ready to write the program, how will you know what code to put in the line to do what you want to achieve?


----------



## Kreij (Jun 4, 2008)

CrAsHnBuRnXp said:


> It doesnt really.
> 
> I can add that it doesnt make a lick of sense to me. I bought a book about a year ago and tried reading up on it. It just doesnt click in my head.
> 
> And when your getting ready to write the program, how will you know what code to put in the line to do what you want to achieve?



No one is born knowing anything about computers or programming.
It is just something that catches their interest and they persue it.

Some are quicker to learn it that others, but anyone can learn it is they devote some time to it.

Some will be better than others in the long run, but that does not mean that a person cannot enjoy programming and make it useful for what they want to do.

If you want to learn. Just ask.


----------



## CrAsHnBuRnXp (Jun 4, 2008)

Kreij said:


> No one is born knowing anything about computers or programming.
> It is just something that catches their interest and they persue it.
> 
> Some are quicker to learn it that others, but anyone can learn it is they devote some time to it.
> ...



I agree with your first statement because it is like that with anything. But that wasnt my point. Programming did catch my interest so I bought a book to learn up on how to do it and as I was reading, it never really made any sense as to why they used what they did. 

I personally learn better with hands on than with reading out of a book. That is why I am good with computer repair. I probably could be too on the networking side of things, but there is also a lot of memorization shit that Id have to know. ADD doesnt help things much either. 

Even if I did/do want to learn about C++, I wouldn't know what to ask let alone have you guys here on the forum begin to teach me via a forum.


----------



## [I.R.A]_FBi (Jun 4, 2008)

Kreij said:


> Okay, IRA, if you want to get over your "fear factor" of VS, try it again and post anything that you are not sure of and we will guide you along.



I want to start something basic (like the code example before this) i want to use VC++08Express, what options should i choose starting up?


----------



## Kreij (Jun 4, 2008)

First, my apologies to IRA. Your thread is wandering from us helping you, to maybe helping anyone who wants to code.
I hope you are not disappointed in that as you may have started a thread that helps more new progarmmers than any so far 



CrAsHnBuRnXp said:


> I agree with your first statement because it is like that with anything. But that wasnt my point. Programming did catch my interest so I bought a book to learn up on how to do it and as I was reading, it never really made any sense as to why they used what they did.



This would be similar to buying a book on how to drive a car. If you don't try it, you just don't get it.



> I personally learn better with hands on than with reading out of a book. That is why I am good with computer repair. I probably could be too on the networking side of things, but there is also a lot of memorization shit that Id have to know. ADD doesnt help things much either.



Hands on is everything. Same with programming. You don't have to memorize everything, you just have to remember where to look stuff up.



> Even if I did/do want to learn about C++, I wouldn't know what to ask let alone have you guys here on the forum begin to teach me via a forum.



You don't have to know what to ask. Just start a thread saying you would like to begin learning. We know what it was like to begin, do not feel intimidated. When I first started programming, all the coders I asked simple questions of were happy to help me. I will always pass that attitude along to anyone who wishes to learn.

If we do not share our knowledge, we have accomplished nothing.


----------



## [I.R.A]_FBi (Jun 4, 2008)

Kreij said:


> First, my apologies to IRA. Your thread is wandering from us helping you, to maybe helping anyone who wants to code.
> I hope you are not disappointed in that as you may have started a thread that helps more new progarmmers than any so far



i dont mind, theyre helpless like me.


----------



## Kreij (Jun 4, 2008)

[I.R.A]_FBi said:


> I want to start something basic (like the code example before this) i want to use VC++08Express, what options should i choose starting up?



What kind of program are you trying to write? That makes a difference on how you start.


----------



## [I.R.A]_FBi (Jun 4, 2008)

i want to  an atm simulation witha login screen


----------



## CrAsHnBuRnXp (Jun 4, 2008)

Kreij said:


> What kind of program are you trying to write? That makes a difference on how you start.



I apologize IRA for hijacking your thread a bit, but it seems you are cool with it. Though, Ill try and keep my comments here brief. 

I wanted to quote Kreij since the whole reason I tried to learn C++ was because I wanted to make my own freeware version of temp monitors. (CPU, GPU, NB, etc)

The whole thing kinda died on me.


----------



## Kreij (Jun 4, 2008)

[I.R.A]_FBi said:


> i want to  an atm simulation witha login screen



I am sorry IRA, I have no idea what you mean.



> I wanted to quote Kreij since the whole reason I tried to learn C++ was because I wanted to make my own freeware version of temp monitors. (CPU, GPU, NB, etc)



That is a great goal, but before you can run you have to learn how to walk.
You must learn the basics to do simple stuff, before you try to tackle how to get in-depth hardware information from your components.

Each of us (including W1zz) started with the basics.

Many people who learn a little about writing game code do the same thing.
They want to go from drawing a square to making Half Life 9.0
It's not going to happen.

Relax, learn and enjoy. 
Programming is fun, but it takes some real effort if you want to really be good.


----------



## [I.R.A]_FBi (Jun 4, 2008)

My doing a program that simulates an Automated Teller Machine.


----------



## Kreij (Jun 4, 2008)

Since the controls on an ATM are all buttons, you could make your simulator look just like one using a GUI.


----------



## [I.R.A]_FBi (Jun 5, 2008)

i want to star t at the basics dont want to jump any steps so id like to use console.


----------



## Kreij (Jun 5, 2008)

[I.R.A]_FBi said:


> i want to star t at the basics dont want to jump any steps so id like to use console.



That is fine, IRA, but why not slowly learn both ?
Using a GUI is just another way of displaying the same information that you are sending to the console window, except with graphics to make the interface more user accessable (I really dislike the term "user-friendly").

Just a suggestion


----------



## calvary1980 (Jun 6, 2008)

you don't know what your missing with dialogs, first one I made I was about 12 or 13 years old think in VB2 or 3 made my own version of notepad that had paint functionality called it "mouseworx" heh thought I was going to be a millionaire  

last program I made with a console was a tcpip.sys thread unlocker because Microsoft likes to lock windows at 10 threads.

consoles are point to point not very fun.

- Christine


----------



## Kreij (Jun 6, 2008)

Thanks Christine,

You are right. The number of controls that are availalbe now is excellent.
You can do almost anything you want with a GUI with very little effort.

Even if the funtionality of the control is lacking something you need, you can always inherit all of the functionality of the control and add to it.

I am sorry you did not become a millionaire.


----------



## [I.R.A]_FBi (Jun 6, 2008)

Im, learning it for school and i dont want to miss anything by being caught up in fanciness and i dont ever want to shoot over my lecturers head (am i being presumptuous?). Plus i dont want to get caught up in maneuvering stuff while my programming logic is weak.


----------



## calvary1980 (Jun 6, 2008)

think of it like a free roam game such as Grand Theft Auto you have an objective but you have multiple ways of completing it some ways will be efficient, some will be inefficient. do not worry about efficiency that takes years of experience but setting a goal or "fanciness" as you call it isn't a bad thing. 

- Christine


----------



## Kreij (Jun 6, 2008)

No way to tell if you are being presumptuous. Your instructor could be a programming genious or just know enough to teach the class.

There is no reason that you cannot continue to work within the boundaries of the console window and at the same time study GUI stuff on your own.

Why do you think that your programming "logic" is weak?
Not knowing the nuances of a language does not imply bad logical analysis.


----------



## [I.R.A]_FBi (Jun 6, 2008)

i guess its jsut practice .. as my program wasnt functioning properly because of a misunderstanding of how "break" works. i guess ill be gettting a Dietel and dietel and learning.


----------



## calvary1980 (Jun 6, 2008)

Kreij's posts give me a head ache. lol

what I meant was, for example the snip I posted in this section "parsesnip" was a tool I wrote it was a simple if you have a link list such as: 

http://john:doe@members.adultsite1.com/members
http://john:doe@members.adultsite2.com/members
http://john:doe@members.adultsite3.com/members
http://jane:doe@members.adultsite4.com/members
http://chris:tine@members.adultsite5.com/members
http://calv:ary@members.adultsite6.com/members

it will take all the duplicate combinations based on set instances ie 3 which would be "http://john:doe@adultsite*.com/members", sort it and re-write the proper format "john:doe" in the output file.

it was about 106 lines of code, it could of been written by 6 people 6 different ways efficient, inefficient, longer, shorter etc it doesn't matter because the objective of the program would of been accomplished. the big picture is something you should be excited about.

personally i'm very efficient I love taking ideas and making them better. like photoshop which is a system hog would love to create my own version and have it utilize half the resources, compatable plugins and open source that would really piss some people off call it "Adob3 Photoshopz".

anyways im sure Kreij would be excited to do your homework 

- Christine


----------



## Kreij (Jun 6, 2008)

Not understanding how a language construct (like the break statement) works is normal for anyone who is learning programming. You will run into this again when you are presented with more abstract concepts.

Do not limit what you learn by what your instructor is teaching you.
You do not want to his/her programming habits to define yours.

Sometimes there is a need to have things explained in a variety of ways before you really understand what is going on. 

Post and we will do our best to make it "click" for you.


----------



## [I.R.A]_FBi (Jun 6, 2008)

his style is to use "void" functions .. i like to return stuff.

ill pick up a bit more on him as i have shis class some more.


----------



## calvary1980 (Jun 6, 2008)

you should take me to class, christine the crazy stripper programmer. i'll challenge your teacher see how well he knows his ASM 

- Christine


----------



## Kreij (Jun 6, 2008)

[I.R.A]_FBi said:


> his style is to use "void" functions .. i like to return stuff..



Keep in mind that if there is no good reason for a function to return a value, then it is just a waste of memory to do so. If you are not going to use the returned value, don't return one.



@Christine : My posts give you a headache?  I had to peruse your parsesnip post line by line to figure it out!  LOL  Keep up the good work and the posting !!


----------



## calvary1980 (Jun 6, 2008)

> I was quite impressed
> 
> Haven't seen proper use of C++ like that before, most peoples code tends to be poorly laid out and people seem to enjoy reinventing the wheel - whereas you've used the collections and pointers like a pro XD
> 
> So where'd you learn to program like that anyway?



Oliver liked it, *bats a scarf around her neck* 

- Christine


----------



## Kreij (Jun 6, 2008)

LOL .... I was not knocking your code. It was more of a testament to me being rusty when it came to what you were doing. 



> christine the crazy stripper programmer



I am not sure how to take that statement.
Do you strip out unnecessary code, or code naked?


----------



## calvary1980 (Jun 6, 2008)

both! 

- Christine


----------



## Kreij (Jun 6, 2008)

LOL ... Thanks Christine, that gave me a good laugh.

I hope that between you, Oliver_FF and I, and anyone else who is willing to help, that we can get IRA to be a coding madman. 

I really appreciate your input to this forum.
I kind of have taken it as my "baby" and I am trying to keep it going strong.
So much good programming info, in any language, that can be shared by people.


----------



## calvary1980 (Jun 6, 2008)

because your such a nice guy I will reward you with this. http://www.techbargains.com/news_displayItem.cfm/123959

- Christine


----------



## Kreij (Jun 6, 2008)

@Chistine : Sorry, never did like KKs, guess I'm just not a donut lover 

@IRA : Get back here and post more code so we can help you.


----------



## [I.R.A]_FBi (Jun 6, 2008)

Ill have to make more code.

But im hungry too so ill have to make dinner (cant buy, saving for upgrades).

BRB


----------



## [I.R.A]_FBi (Jun 13, 2008)

i want to read in a set amount of characters into a variable

char ISBN [13];

how do i do it?


----------



## Kreij (Jun 14, 2008)

It depends on where you are getting the characters from. Give us a little more information.
Is this user input? Is it from another variable? Maybe a file?


----------



## [I.R.A]_FBi (Jun 14, 2008)

user input i want to make sure the user inputs only the 13 numbers


----------



## Kreij (Jun 14, 2008)

Read the input into a variable.
Check the length of the string in the variable.
If it is not exaclty 13 characters, throw an error and return them to the input prompt.


----------



## Oliver_FF (Jun 14, 2008)

You can use the fgets() function to ensure that characters are read in up to, and not more than, 13 characters:

http://www.cplusplus.com/reference/clibrary/cstdio/fgets.html


```
char ISBN [13];
fgets(ISBN, 13, stdin);
```

If it's from file or whatever replace stdin with your FILE* object, etc


----------



## [I.R.A]_FBi (Jun 15, 2008)

god bless oliver


i got thsi assignemnt to do



> QUESTION  ONE
> Consider a class named Employee with data members: name and id. All employees have the following behaviour:
> (i)	setEmployee – sets values to instance variables.
> (ii)	showEmployee – print the information of the employee
> ...



ima do what i can and post what i did


----------



## [I.R.A]_FBi (Jun 16, 2008)

question 2


```
#include <iostream.h>
#include <conio.h>
#include <string.h>

class account
{
      private:
              float interestRate;
              float balance;
              
      public:
             account(float,float);
             void calculateInterest();
             void setInterestRate();
             void getAccount();
};

account::account(float bal, float in)
{
     balance = bal;
     interestRate = in/100;
}

void account::calculateInterest()
{
     cout << "\nYour new balance after interest calculation is: $" << (1+interestRate)*balance;
     cout << "\nYour current interest rate is: " << (100*interestRate) <<"%";
     cout << "\nYour interest payment for this month is: $" << interestRate*balance;
     
     balance = (1+interestRate)*balance;
}
 
void account::setInterestRate()
{
     float intrate;
     
     cout << "\nEnter the new interest rate in percent: ";
     cin>> intrate;
     
     interestRate = intrate / 100;
}
 
void account::getAccount()
{
     cout << "The current balance is: $" << balance;
     cout << "\nThe current interest rate is: " << interestRate*100<<"%";
}

int main()   
{
    account mine(3000,7);
    
    mine.getAccount();
    mine.calculateInterest();
    mine.setInterestRate();
    
    getch();
    
    return 0;
}
```


----------



## CDdude55 (Jun 16, 2008)

Well...flux capacitor,


----------



## [I.R.A]_FBi (Jun 16, 2008)

```
#include <iostream.h>
#include <conio.h>
#include <stdio.h>

class employee
{
      protected:
              char employeeName [20];
              char employeeIDNumber [10];
              
      public:
             employee();
             void setEmployee();
             void showEmployee();
};

employee::employee()
{
        //Whatever
}

void employee::setEmployee()
{
     cout << "Enter the employees name: ";
     fgets(employeeName, 20, stdin);
     cout << "Enter the employees ID number: ";
     fgets(employeeIDNumber, 10, stdin);
}

void employee::showEmployee()
{
     cout << "\nThe employees name is: " <<employeeName;
     cout << "The employees ID number is: " << employeeIDNumber;
}

class staff:public employee
{
      private:              
              float hours;
              float rate;
              float pay;
      
      public:
             staff();
             void showEmployee();
             void setEmployee();
             void updateHrRt();
             void computePay();
};

staff::staff()
{
     //whatever 
}

void staff::showEmployee()
{
     cout << "\nThe employees name is: " <<employeeName;
     cout << "The employees ID number is: " << employeeIDNumber;
}

void staff::setEmployee()
{
     cout << "Enter the employees name: ";
     fgets(employeeName, 20, stdin);
     cout << "Enter the employees ID number: ";
     fgets(employeeIDNumber, 10, stdin);
}

void staff::updateHrRt()
{
     cout << "Input the new hourly rate: ";
     cin >> rate;
     cout << "Input the hours completed: ";
     cin >> hours;
}

void staff::computePay()
{
     cout << "Enter the amount of hours completed: ";
     cin >> hours;
     cout << "Enter the hourly rate: ";
     cin >> rate;
     
     if (hours > 40)
         pay = ((hours - 40)*(rate * 1.5))+( 40*rate);
     else
         pay = rate * hours;
         
     cout << "Your pay is: " << pay;
}

class faculty:public employee
{
      private:
              int rank;
              float salary;
      public:
             faculty();
             void showEmployee();
             void setEmployee();
             void updateRnk();
             void computePay();
};

faculty::faculty()
{
      //whatever
}

void faculty::showEmployee()
{
     cout << "\nThe employees name is: " <<employeeName;
     cout << "The employees ID number is: " << employeeIDNumber;
}

void faculty::setEmployee()
{
     cout << "Enter the employees name: ";
     fgets(employeeName, 20, stdin);
     cout << "Enter the employees ID number: ";
     fgets(employeeIDNumber, 10, stdin);
}

void faculty::updateRnk()
{
     cout << "Please enter the new rank of " << employeeName;
     cin >> rank;
}

void faculty::computePay()
{
     switch(rank)
     {
         case 1:
              salary = 250000;
              cout << employeeName << ", your salary is: $" << salary;
              break;
              
         case 2:
              salary = 200000;
              cout << employeeName << ", your salary is: $" << salary;
              break;
              
         case 3:
              salary = 120000;
              cout << employeeName << ", your salary is: $" << salary;
              break;
     }
}
     
       

int main()
{
    employee FBi;
    faculty FB;
    
    FBi.setEmployee();
    FBi.showEmployee();
    
    getch();
    
    return 0;
}
```

part uno


----------



## Oliver_FF (Jun 16, 2008)

Cool, thats not a bad effort 

Nit picking though:
q1 - with an inheritance hierarchy you're getting the data members down to the subclasses, but the functions can also be passed down. For instance Staff and Faculty share the same functions showEmployee() and setEmployee(), you can get rid of those and simply make the declarations in Staff protected?

q2 - I had the impression that setInterestRate() should take the value you want to change it to as a parameter, not get it from the command line?

But yeah, looking good


----------



## Kreij (Jun 16, 2008)

I agree. Looking good FBi


----------



## [I.R.A]_FBi (Jun 16, 2008)

thx guys .. going reason witht eh lecturer


----------



## [I.R.A]_FBi (Jun 16, 2008)

ima ask him for moar work to do


----------



## [I.R.A]_FBi (Jun 24, 2008)

1.	Briefly  discuss  the  differences between  multilevel  and multiple inheritance.  	        
2.	Write the program code that validates an email address by checking the presence of “@” symbol.


----------



## Deleted member 3 (Jun 24, 2008)

[I.R.A]_FBi said:


> 2.	Write the program code that validates an email address by checking the presence of “@” symbol.



instr()


----------



## [I.R.A]_FBi (Jun 24, 2008)

thanks for the hint


----------



## Oliver_FF (Jun 24, 2008)

[I.R.A]_FBi said:


> 1.	Briefly  discuss  the  differences between  multilevel  and multiple inheritance.



For this you might want to consider the implications on storing collections of objects... Do you know what Polymorphism is?


----------



## [I.R.A]_FBi (Jun 24, 2008)

not entierly


----------



## Oliver_FF (Jun 24, 2008)

Ok. Suppose this example:


```
Class Stationary;
Class Pen [inherits] Object;
Class Pencil [inherits] Object;
Class Paper [inherits] Object;
```

So the superclass is Stationary, and it has 3 subclasses Pen, Pencil and Paper.

If you create an object of type Stationary:

```
Stationary thisStationary;
```

Then Polymorphism allows you to story any item who'se dynamic type is that of Stationary or anything that inherits from it. Thus the following is perfectly legitimate:

```
Stationary thisStationary = new Pen();
Stationary thisStationary = new Paper();
```

This is particularly useful in programming - say you are modelling an office. You need a collection of all the stationary in the room but don't want to mess around with 3 seperate lists (one for pen, one for paper, one for pencil). So, you create a collection of type Stationary and you can insert into it all of the items. Note that if you do this, you can only use the items you pull out of the collection as if they were objects of the superclass. You need to down-cast the objects to their original classes.


----------



## [I.R.A]_FBi (Jun 25, 2008)

DanTheBanjoman said:


> instr()



can i get a next hint?


----------



## Kreij (Jun 25, 2008)

Interesting Oliver_ff. I guess we have all be exposed to OOP in different ways and that shapes how we would align the objects in the heirarchy.

For instance, I would go with

```
Class WritingMedia
Class WritingUtelnsil
```

Then inherit from those base classes to produce the next level

```
Class Paper : WiritingMedia
Class Parchment : Writing Media
Class Pen : WritingUtensil
Class Pencil : Wirting Utensil
```

You could then use

```
Class ColoredPaperWithPen : Paper, Pen;
```

Maybe I'm wrong. But just a thought.


----------



## [I.R.A]_FBi (Jun 25, 2008)

I have no idea how to manuplat strings

basically the user is going to input a string and then i search the string for an "@" .... if i get that i can send backa true (use a bool?) and thats what i use to determine if the input string is valid


----------



## Kreij (Jun 25, 2008)

Okay FBI,

I am not going to give you code. You need to learn the underlying way that this stuff works.
A string is actually an array of characters.
In the most basic sense you can get the string from the user, and then look at each character position in the string to see if it contains the "@" symbol.
You need to learn how to do this.
It is more important to learn to be able to do it by brute force than to use a method in the languange.

Something like...

```
private Boolean checkforgoodstring(string myString)
{
    goodstring = false;
    Foreach (char character in myString)
    {
         if character="@" then goodstring = true;
    }
    return goodstring;
}
```

I am used to C#, so change syntax as needed.


----------



## [I.R.A]_FBi (Jun 25, 2008)

trying something


----------



## Kreij (Jun 25, 2008)

Depending on the language you will have to access the array manually by the index of the characters.

using syntax like myString[index];

So for instance...

```
String myString = "FBI";
```

That means that myString[0] is equal to the letter "F"
myString[1] is "B"
and myString[2] is "I"

IF the string arrays are zero based (which they usually are)


----------



## [I.R.A]_FBi (Jun 25, 2008)

for loop?


----------



## Kreij (Jun 25, 2008)

For loop = 0 until loop > the length of the string do something

Understanding how variables are stored in memory is really important.
Especially if you are using C++ with pointers.

Sorry FBI, gotta go. Work calls early in the morning.
I will check this thread as soon as I can to help you.


----------



## [I.R.A]_FBi (Jun 25, 2008)

```
#include <iostream.h>
#include <conio.h>
#include <string>
using std::string;

int it;
string Input;

bool checkForAt(string);

bool checkForAt(string th)
{
     bool isit;
     
     it = th.size();
     
     for(int count = 0; count < it; count++)
     {
             if (th[count] == '@')
                isit = 1;
     }
     
     return isit;
}

int main()
{
    cout << "Enter an email address: ";
    cin >> Input;
    if(checkForAt(Input) == 1)
    {
         cout<<"This is a valid address";           
    }
    else
    {
        cout <<"This is not a valid address";
    }
    
    
    getch();
    return 1;
}
```


bumboclaat!


----------



## Oliver_FF (Jun 25, 2008)

Whenever you want to work with Strings, the first place I always check is here:
http://www.cplusplus.com/reference/clibrary/cstring/

It lists every library function in C/C++ for manipulating strings. If you look halfway down the page you'll see this one:


> strpbrk	 Locate character in string (function)



Well, that sounds hopeful, so click on that and read on...



> Locate character in string
> 
> Returns a pointer to the first occurrence in str1 of any of the characters that are part of str2, or a null pointer if there are no matches.
> 
> ...



So i'm thinking "I've got this function, that will return a pointer to a location inside a String of any character I want, provided it exists. If it doesn't exist inside my string it returns NULL."


```
bool checkForAt(string th)
{
    return strpbrk(th, "@");
}
```


----------



## Oliver_FF (Jun 25, 2008)

Kreij said:


> Interesting Oliver_ff. I guess we have all be exposed to OOP in different ways and that shapes how we would align the objects in the heirarchy.
> 
> For instance, I would go with
> 
> ...



I was taught inheritance last year in my university degree using Java, which only supports single inheritance  It makes the hierarchy and the code a lot simpler but you have to spend a lot more time thinking about how to get your functionality down to the subclasses.


----------



## Deleted member 3 (Jun 25, 2008)

[I.R.A]_FBi said:


> can i get a next hint?



instr("test@test.com", "@") would return 5, as the first appearance of @ is the fifth character.
Basically if instr() returns anything there is an @ you're good. Though you can use len() to determine the length of the string and make sure someone doesn't just put @ as e-mail.


----------

