• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

FBi's running C++ questions

Joined
May 19, 2007
Messages
7,662 (1.15/day)
Location
c:\programs\kitteh.exe
Processor C2Q6600 @ 1.6 GHz
Motherboard Anus PQ5
Cooling ACFPro
Memory GEiL2 x 1 GB PC2 6400
Video Card(s) MSi 4830 (RIP)
Storage Seagate Barracuda 7200.10 320 GB Perpendicular Recording
Display(s) Dell 17'
Case El Cheepo
Audio Device(s) 7.1 Onboard
Power Supply Corsair TX750
Software MCE2K5
Clearscreen with anything else other than clrscr

Anyone can help me
 
need to

#include <stdlib.h>

system("cls");
 
how do i make the screen pause for 5 seconds?
 
// windows.h needs to be included for this...

void DelaySecs(int secs)
{
unsigned long int t=GetTickCount()+(1000L*secs);
while(GetTickCount()<t)
{ /* Wait !!!*/ }
}
 
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..
Code:
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.

Code:
#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.
 
Last edited:
god bless you.
 
god bless you.

Thanks, that's very kind of you. :toast:

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).

Code:
#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 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 ...
 
Code:
//  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
 
Ok these kind of bugs are rather obscure, but it relates to your use of cin and gets...

Code:
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
Code:
int a, b, c;
String s1, s2;
printf("String: %s, %i -- %i; %s +-+ %i", s1, a, b, s2, c);
might produce:
Code:
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.
Code:
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:
Code:
a = 5
b = 6
c = 5
s1 = bob
s2 = test
 
thanks, it helped.
 
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 ;)
 
whats a good free compiler, currently uing dev cpp
 
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.
 
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!
 
It was included but it still says "clrscr undeclared, first use of function"
 
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.
 
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?
 
Back
Top