PDA

View Full Version : Stupid c++ question...how do you pause output in a terminal program?



Shadow Skill
16th September 2004, 06:32 AM
I am using c++, just kind of playing around seeing how much I (don't) remember. One thing I noticed is that outside of borland compilers it is apparently a mystery as to how to pause console output. I tried system("PAUSE"); and I get the following
EXECUTING:
/home/kevin/Projects/shopping/src/shopping
----------------------------------------------
This program is intended to test how much I remember and have forgotten.
Hello customer, I will now list the available items.
1. Hot dogs
2. Nachos
3. Sub sandwich
sh: line 1: PAUSE: command not found

----------------------------------------------
Program exited successfully with errcode (0)
Press the Enter key to close this terminal ...



Now if the program broke I would be one step closer to solving this issue but it doesn't even complain about system("PAUSE"); what command can I use to pause output. While I am at it what command can I use to clear console output, since I have a sneaking suspicision that system("cls"); wont' work either

Here is the code in question:


#include <iostream>
#include <cstdlib>
using namespace std;
int customer();
int main()
{
cout << "This program is intended to test how much I remember and have forgotten." <<endl;
customer();
system("PAUSE");
return 0;
}


Also is there any way to not have to include the same exact header files in member functions and still keep those member functions in seperate files? (It's an organizational thing that I don't want to let go of because it makes things easy to focus on for me.)

jcstille
16th September 2004, 06:38 AM
well what are you waiting for. Like a user to select a product. Because an easy way would be have a cin of whatever. then it would wait for input. Either that or write a loop that executes many many times, and that is pascal style.

Shadow Skill
16th September 2004, 06:54 AM
well that is one way to do it, but that is hokey, I just need a general pause command so that as this program gets longer and longer the output is going to end up being so crazy that it won't be readable. I want to have it so that it waits for the user to press exit just like it waits for the user (me in this case.) to press entre before the terminal closes.

Do you know of a clrscr() type command system("cls"); doesn't work at all and generates no errors either.... (I know I could do 25 new lines but its hokey [I'll have to look around for a c++ example of how to actually make a genuine clrscr() function, I know I saw one way back.] )

ghaefb
16th September 2004, 07:18 AM
Maybe you can use 'sleep NUMBER' command. The NUMBER is how long in seconds to sleep.
You are using DOS command 'cls' unix command is 'clear' to clear the screen.

Shadow Skill
16th September 2004, 10:54 AM
Thanks for the info..I'll try it next time I boot Fedora, that would explain why it compiles and runs with no real errors.

PompeyBlue
16th September 2004, 09:21 PM
As has already been eluded too, if you want to pause then the easiest way of doing this is to just sit in a loop for a period of time.

for(loop=0;loop<5000000;loop++)
{
// I'm paused
}

I guess you are a newbie starting to put code together, and so that for loop will probably do for now, but it's not a very good pause at all.

Under release builds (i.e. get the compiler to optimise the code) it would probably notice that the pause code does nothing and remove it, thus removing your pause.

What you are trying to do is tackle 3 basic problems at once, these are:

1. Some kind of processing (remembering what somebody ordered)
2. Some kind of screen IO
3. A system timer function

For the screen IO & System timer, you have lots of different options open to you depending on what you are trying to achieve. If you want textured, lit, polygons then GLUT & OpenGL would be a good library to use, and the setting up and using of timers and IO under those is well documented here: http://www.opengl.org/

If you are looking for a more GNOME style interface, then you are best using KDEVELOP & the KDE project, other's can give you more info.

As you are just experimenting with code though, the way you are going is probably the best. Issue the SYSTEM command and just call native stuff. Good luck learning to program, it's a steep learning code but gets substantially easier later on, and it will reward you richly if\when you master it!

tashirosgt
16th September 2004, 10:02 PM
ShadowSkill,
Do you want a pause that is not controlled by the user or do you want the screen to pause until the user presses a key? And do you want the user to have to press Enter after he presses the key? And should the method be portable or will you settle for one that only works in Unix/Linux?

jcstille
16th September 2004, 10:30 PM
You can try this If you include the windows.h file you can use the Sleep();command, with the duration within the parenthesis.

Shadow Skill
17th September 2004, 12:01 AM
I want the program to simply wait until the user presses entre before continuing with execution (I miss getch(); ) I remember the sleep() function dimly, but it had not occured to me because I was going for a pause that would last until the user pressed a key (I don't know how to make it so that ONLY Entre would work...I never learned anything about how to bind keys even thougfh I knew it could be done.....) I am going for something that will work on both *nix and windows.

Pompey:
Yea I am just experimenting right now, trying to get at least some of the stuff I used to know to come back to me, I am very rusty I didnt keep up with it after high school [about 2 years now] and most of what I knew and was avle to do with relative consistency has all but dissapeared now. :( My goal is to expand the above code as I pick up new (and old) things to sort of keep it in my head before my actual courses start [even though it probably won't c++ or even c#, I hope it ends up being c# .net though. It better not be VB or Java *shudders]

tashirosgt
17th September 2004, 03:44 PM
I've asked the same question as you. If you are just fooling around you can use the system(...) command to have a shell read some variable (which it will not use.) This probably looks like
system("read $variable");
But I'm not sure about the exact syntax.

If you want to write a "serious" Unix/Linux terminal program then you should look a the ncurses functions - or that is what my advisors tell me. There is a getch() function ( man 3 curs_getch ). I've never done this because one would have to learn the functions that set up the terminal. ( If you figure out how to set one up, please post an example!)

Of course, my advisors always ask me "Why do you want a terminal program? Just write a gui interface. It's simple nowadays.". That may be true. But I prefer to write C programs using the system call rather than writing scripts. And scripts aren't gui.

Chas.H
18th September 2004, 12:05 AM
I am using c++, just kind of playing around seeing how much I (don't) remember. One thing I noticed is that outside of borland compilers it is apparently a mystery as to how to pause console output. I tried system("PAUSE"); and I get the following ....
Shadow Skill,
Sometimes when I have a hard time finding the function I want, I just make one.
Check This out, I did it in KDevelop...


#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <iostream>
#include <cstdlib>
#include <time.h>

using namespace std;
void delay(int num)

{

int now, later;

time_t seconds; // time_t struct



now = time(NULL); //get current time

later = now + num; //determine how long from now to stop (future time)

while(time(NULL) < later)

{/*do nothing*/} /*this just hangs out until it reaches future time*/
return;

}

int main(int argc, char *argv[])
{
cout << "Hello, world!" << endl;
delay(3); /*******************call the function***************/

cout << "Goodbye world!" << endl;


return EXIT_SUCCESS;
}


delay() is the function I made up. It takes an int for the argument. I included the main() to show how to call it. In this case the number 3 is the delay time in seconds. It lest you be very specific on how long a delay you want to put in your app.

I hope this is what you are looking for.

Shadow Skill
18th September 2004, 02:18 AM
I don't know if you know this but there was at least a delay function in turbo c++ [My high school was too cheap to get us real IDE's, this being betwwen 2k1 and 2k3..so it isnt like proper non dos IDE'S were still buggy etc.] that behaved in almost the exact same manner as the code above except that that it took time in milliseconds [I might be confusing the data entry method with sleep(); .)so you would need to do delay(3000); for 3 seconds of delay time. But this and sleep() will come in handy, thanks alot..Now if only I could remember how to make header files and proper classes I could make the above portable.[IMO one's that can be called with just the function name itself none of that hokey constructor crap.] (Cracks open standard c++ bible [probably sorely outdated by now.] )

Chas.H
18th September 2004, 04:32 PM
Actually, no. The units in my delay are seconds.
delay(3) = 3 seconds
delay(3000) = 50 minutes

After posting, I was thinking I could use a float for the argument so you could use fractions of seconds. I had something similar in a header file but also forgot how to do it. (I use Delphi and php at work. Also, *gulp* windows 2000.)

Time to crack my book.

By the way, I still use a C++ book from 1996. ;)

Shadow Skill
18th September 2004, 09:05 PM
Heh I need one on building GUI's the fundamental stuff appears to be pretty much the same, but the book I have is alittle more windows centric, and only teaches you how to do stuff for console commands. :( Do you know of any c++ books that are written in english (not nerd speak.) that handle GUI's specifically *nix gui programming? (would prefer something that talks about things I can use on windows as well.) To be honest I am alitttle intimidated by some of the c++ code I have seen that is used to make dialouge boxes and such. :D

tashirosgt
19th September 2004, 05:22 PM
My opinion is that the typical C++ material on guis ( be it books, docs or the experts who pose in the various mailing lists) assumes a veritable mastery of C++. This is complicated by the fact that there are many different libraries for writing guis. For C++, one has Qt, Gtkplus, WxWindows and (my favorite) the Fox toolkit. If you want a simple way of doing guis, I'd advise learning a new language! For example Tcl/Tk .

Shadow Skill
21st September 2004, 07:03 PM
Ok this is the same program as before only now I decided to add in an escape sequence and give the option to make another selection. It complains that in function customer() x is undeclared...the thing is its a global variable [at least it should be global.] Here is the code from main() and customer()
#include <iostream>
using namespace std;
int customer()
{
int choice;

cin>>choice;

switch (choice)
{
case 1: cout<<"You chose Hot Dogs."<<endl;break;
case 2: cout<<"You chose Nachos."<<endl;break;
case 3: cout<<"You chose Sub sandwich"<<endl;break;
case 999:x=1;break;
default: cout<<"Invalid selection."<<endl;break;
}


return 0;
}

Note that the duplicate include is there because I put member functions in seperate files for organizational purposes.

Here is main()

#include <iostream>
#include <curses.h>
#include <cstdlib>
using namespace std;
int customer();
int option();
int x=0;
int main()
{
char escape_choice;
cout << "This program is intended to test how much I remember and have forgotten." <<endl;
sleep(3);
system("clear");
do
{
option();

customer();
cout<<"Continue? Yes,No";cin>>escape_choice;
switch(escape_choice)
{
case 'y':cout<<"Ok.";system("clear");break;
case 'n':x=3;break;
}

}while(x=0);
return 0;
}
What am I not doing right here?

tashirosgt
21st September 2004, 08:18 PM
Should you main say "extern int customer();"

Chas.H
21st September 2004, 09:19 PM
If your goal here is to have the programme wait for user input, cin will do that for you. I don't see what you intend the while loop to do.

Again I made this in KDevelop,
I think this does what you want:


#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <iostream>
#include <cstdlib>
#include <curses.h>

using namespace std;
int customer(void);
int customer()
{
int choice;

cout << "enter a choice: 1, 2, or 3" << endl;
cin >> choice;

switch(choice)
{
case 1:
{
cout << "Hot Dogs" << endl;
break;
}
case 2:
{
cout << "Nachos" << endl;
break;
}
case 3:
{
cout << "Sub Sandwich" << endl;
break;
}
default:
{
cout << "Invalid selection" << endl;
}
}
}

int main(int argc, char *argv[])
{

customer();

return EXIT_SUCCESS;
}


once again I haven't mastered writing header files :o

Shadow Skill
21st September 2004, 10:56 PM
I wanted the do while to make the entire program repeat itself as long as x=0; . This was a technique that was totally indespensible to me when I finally began to incorporate loops into programs I did for my old high school classes it totally infuriates me that I can't even do that anymore.. :( God I suck so bad now, almost as much as when I first started....

Chas.H
22nd September 2004, 12:49 AM
You do the test at the end of the while loop (x=0) which is good, but you need to use the double equal sign (x==0). This is the logical equal. The one you used sets x equal to 0 so the while will always return true.

Shadow Skill
22nd September 2004, 02:42 AM
Crap you're right.....I totally forgot about the difference between the assignment operator and the one we use for logical expressions.. (logical operator?) Thing is it didn't even execute at all, I should have gotten an infinite loop, now that I see that problem in particular. It still doesn't explain why it claims int x is undeclared when it should be declared for all of the functions within the program. Isn't there an actual global keyword?

tashirosgt
22nd September 2004, 03:23 PM
One of basic guidelines in modern programming is to avoid using global variables. When you do use them then some things must be cleared up. You seem to think that any variable (like x) declared outside any function will be recognized inside any function. I think this is only true when the function is in the same file as the declaration. That is why the "extern" declaration is usually needed.

Suppose you have

int x = 0;


in one file. Then in the other file, you must have something like

void customer()
{
extern int x;
....

or it might look like:

extern int x;

void customer()
{
....


To write complicated programs, you need to learn how to use #include files. The first thing one would try with header files doesn't work. Namely if you make a file:
// file MyHeader.h
int x;

and then, in another file, have

#include "MyHeader.h"
void customer()
{
....
}
and in main.cpp you have

#include "MyHeader.h

int main()
{
...
}

Then you will probably get the error message that x is defined more than once - and it is.


If you don't want to keep typing the extern declarations you have to use some scheme like:

// file MyHeader.h

#ifdef ALLOCATE // (or whatever keyword for "create some global variables" you want to use)

int x = 0;

#else

extern int x;

#endif

Then the function looks like:

#undef ALLOCATE
#include "MyHeader.h"

void customer()
{
....
}

and main.cpp would look like:

#define ALLOCATE
#include "MyHeader.h"

int main()
{
....
}

Having said this, there are still other problems in writing header file to overcome. Suppose the file BobsHeader.h includes MyHeader.h. Then you always have to be careful not to include both BobsHeader.h and MyHeader.h in the same file. Otherwise you get two declarations of x. This is why C++ header files use "guards", they usually look like this:

// file MyHeader.h

#ifndef LONG_NAME_THAT_I_WILL_ONLY_USE_IN_THIS_HEADER_FILE
#define LONG_NAME_THAT_I_WILL_ONLY_USE_IN_THIS_HEADER_FILE

....

#endif

This way, if the file is included twice, the second time has no effect.

Chas.H
23rd September 2004, 01:53 AM
Back in the day(early 80's), when I wrote C programmes (not C++) I used to write header files which were just a load of functions. Now, with modern C++, header files should contain classes instead of simple functions, with their own private variables and member functions(methods).
I think tashirosgt would agree, eh?

Chas.H
23rd September 2004, 02:07 AM
I wanted the do while to make the entire program repeat itself as long as x=0; .

It looks to me like you want just the customer input to repeat when needed.

Try something like this:


char doAgain;
cout << "Do another? Y/N" << endl;
cin >> doAgain;
if(doAgain == "y" || doAgain == "Y") // || = logical or
{
customer();
}

Put this code at the end so when the if returns false, programme control falls to the last line: return EXIT_SUCCESS;

Chas.H
23rd September 2004, 02:47 AM
Back in the day(early 80's) when I wrote C (not C++) I used to write header files that were simply a load of functions. Now, with modern C++, it is better to use header files mainly for classes that have their own private variables and functions(methods). These can return a value that you can use in your main programme:


className foo; //instantiation of the class
answer = foo.function(); // calling one of the class's member functions


This will protect all your variables.

Shadow Skill
23rd September 2004, 04:44 AM
I used to just use define to achieve a similar effect when performing simple computations..because I could...:D Is it workable for me to simply create a headerfile specifically geared towards this type of logic (I don't know if that is the word I want to be using here.) so that I could create a variable that would be unique regardless of the program. You are indeed right about the globals and thier problems...now that I think about it I should probably just pass the value of X back to the main so that it may be tested by the do while(); *cracks open book and flips to passing variables.....

PompeyBlue
26th September 2004, 03:10 PM
Back in the day(early 80's) when I wrote C (not C++) I used to write header files that were simply a load of functions. Now, with modern C++, it is better to use header files mainly for classes that have their own private variables and functions(methods). These can return a value that you can use in your main programme:


className foo; //instantiation of the class
answer = foo.function(); // calling one of the class's member functions


This will protect all your variables.

This is an interesting question. On large projects it can become unwieldy to have a programmer write an access function for each and every member variable.

However, the beauty of access functions is that if the class changes, as long as you keep the same interface, then everything still works.

I.e. I wrote a physics class which had the access function "GetVelocity()". Later on, I changed integrator to Verlet (which doesn't store a value for Velocity) but I changed the GetyVleocity member so instead of returning the variable it computed the Velocity and returned that. This meant I didn't have to changes reams and reams of code which was accessing vVelocity.

I really can't find an easy way of describiong when you should use access functions, and when you should use member variables. I guess the purist would say always use access functions, but with production being so time and money constrained there is no choice, in the real world, but to pull some of the member variables out manually :(

Alladin
4th December 2007, 02:34 PM
I think what you are actually looking for is a non-system dependant pause till the user hits enter. I use this all the time to ensure my software is not platform dependant.

This is the C++ version and only requires that you include iostream and use namespace std

this is a pause till the user hits any key and a generic clear screen
built into one function.

-------------------------------------------------------------------
#include<iostream>

using namespace std;

void PauseAndClear();

int main
{
cout << "Some text or stuff";
PauseAndClear();

return 0;
}

// This is the function for both

void PauseAndClear()
{
char cGarbage;
cin.clear();
cin.ignore(cin.rdbuf()->in_avail());
cout << "\n**************Press any key to continue***************" << flush;
cin.get(cGarbage);
cin.clear();
cin.ignore(cin.rdbuf()->in_avail());

// if u dont want a clear screen, dont include this "for" statement

for (int i = 20; i > 0; i--)
cout << '\n';
cout << endl;
return;
}

Compliments of Alladin -- CNT :cool:

Tashiro
4th December 2007, 11:45 PM
Are you aware you replied to a 3 year old thread?

anonymouss
1st January 2011, 06:01 AM
I know that this is a three year old thread, but the answer is rather simple and anybody reading this should know the answer.

When the curses.h is expanded, the cpp file becomes:


#include <iostream>
#include <iostream>
using namespace std;
int customer()
{
int choice;

cin>>choice;

switch (choice)
{
case 1: cout<<"You chose Hot Dogs."<<endl;break;
case 2: cout<<"You chose Nachos."<<endl;break;
case 3: cout<<"You chose Sub sandwich"<<endl;break;
case 999:x=1;break;
default: cout<<"Invalid selection."<<endl;break;
}


return 0;
}
#include <cstdlib>
using namespace std;
int customer();
int option();
int x=0;
int main()
{
char escape_choice;
cout << "This program is intended to test how much I remember and have forgotten." <<endl;
sleep(3);
system("clear");
do
{
option();

customer();
cout<<"Continue? Yes,No";cin>>escape_choice;
switch(escape_choice)
{
case 'y':cout<<"Ok.";system("clear");break;
case 'n':x=3;break;
}

}while(x=0);
return 0;
}

Even without the double includes and the double using directives, it is plain to see that x is defined and declared after customer. X is global and no extern is nessesary. The thing to remember is that what include does is tell the compiler to take the stuff in the stuff in the specified file and treat it as if it was in the source file at that point. The two solutions for this would be to either only declare a prototype in the header and define the function itself either after x or in another source file.

DBelton
1st January 2011, 08:03 AM
holy necrophilia batman! :D

you responded to a three year old post, which was a in reference to a post that is now over 6 years old. :D

But it is good that there are solutions being added to threads. could help someone out in the future looking for an answer.

anonymouss
3rd January 2011, 05:31 AM
That was what I was thinking.

Amr Hesham
4th January 2011, 08:18 PM
cin.get();

Vouters
23rd January 2011, 09:55 PM
What about the C pause() statement ?

COKEDUDE
15th November 2013, 03:14 AM
What about the C pause() statement ?

I know this is old but I hope this will other people. The C pause() statement is VERY bad to use. It will make your C and C++ programs not work in Linux.


system("PAUSE")

The getchar() is much better to use. It holds your window open.


getchar()

This explains this in more details.

http://www.gidnetwork.com/b-61.html

ocratato
15th November 2013, 04:41 AM
While cin.get() or getchar() can be useful, sometimes you don't want or cannot have a stdin for the process - server daemons for example. In this case you can just have the process raise a SIGSTOP. Of course you will then need to send it a signal to have it resume, but that isn't in the program being tested.


#include <iostream>
#include <signal.h>

using namespace std;

int main( int argc, char *argv[] )
{
cout << "starting..." << endl;
cout << "stopping..." << endl;

raise( SIGSTOP );
cout << "resuming..." << endl;
cout << "done" <<endl;
return 0;
}

which runs like this:


[brenton@acer Forum]$ ./stop &
[1] 11118
[brenton@acer Forum]$ starting...
stopping...

[1]+ Stopped ./stop
[brenton@acer Forum]$ kill -s SIGCONT 11118
resuming...
done
[brenton@acer Forum]$
[1]+ Done ./stop
[brenton@acer Forum]$

Gareth Jones
21st November 2013, 02:02 AM
holy necrophilia batman! :D

Wow indeed; it’s still going. I think it would be a crime to kill a thread so old… Luckily this “low-level” stuff stays relevant for a long time.