473,385 Members | 1,942 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Is there any command like Pause or Nope in C++?

I just want the programme to stop for a while.
Thanks.

Jan 29 '06 #1
38 3950
"Jackie" writes:
I just want the programme to stop for a while.


Your best bet is probably the system() function since
it lets you interact with the OS. For example, in Windows, try
system("pause");
Jan 29 '06 #2
Jackie wrote:
I just want the programme to stop for a while.
Thanks.


Do you want the program to stop until you hit enter? If so, use cin like:

string str;
cin >> str;

That will stop the program till you press the Enter key.

Alvin
Jan 29 '06 #3
Tom
On Sun, 29 Jan 2006 08:43:57 -0800, "osmium" <r1********@comcast.net>
wrote:
"Jackie" writes:
I just want the programme to stop for a while.


Your best bet is probably the system() function since
it lets you interact with the OS. For example, in Windows, try
system("pause");


In C type logic ... I create a dummy string and use gets() to pause a
program.

#include <stdio.h>

char junk[81];
printf("routine_name(%d):"
" hit return to continue the paused program ...\n", __LINE__);
gets(junk);

-----------------

gets(junk); is good for clearing erroneous key strokes before
prompting for keyboard input in programs as well.

If erroneous keystrokes occur and the pause is critical ... you should
test for a null string. The following echos the erroneous keystrokes:

if(junk[0])
{
printf("routine_name(%d): junk = %s\n", __LINE__, junk);
gets(junk);
}

The "__LINE__" macro tells you the exact line and by including the
name of the routine in your printf statement you can find this pause
point easily.

Setting a break point would work too. But I usually don't debug using
break points. I like print statements. I often write them to log files
and turn the pause feature on and off with a #define.

#define pause 1
if(pause) gets(junk);

My apologies for not having sufficient C++ skills to make the code
clean and gorgeous. Fortunately C is fully supported in C++. My bet is
a C++ guru in here will teach us both a better way. :))

Jan 29 '06 #4
Tom wrote:
On Sun, 29 Jan 2006 08:43:57 -0800, "osmium" <r1********@comcast.net>
wrote:
"Jackie" writes:
I just want the programme to stop for a while.
Your best bet is probably the system() function since
it lets you interact with the OS. For example, in Windows, try
system("pause");


In C type logic ... I create a dummy string and use gets() to pause a
program.

#include <stdio.h>

char junk[81];
printf("routine_name(%d):"
" hit return to continue the paused program ...\n", __LINE__);
gets(junk);

That is a *HUGE* security risk. What if I type more than 80 characters?
I suddely make your program _read my input_ into the memory that wasn't
designated for it.
-----------------

gets(junk); is good [..]


No! It's _awful_. Never use it. NEVER!

V
Jan 29 '06 #5
Alvin wrote:
Jackie wrote:

I just want the programme to stop for a while.
Thanks.

Do you want the program to stop until you hit enter? If so, use cin like:

string str;
cin >> str;

That will stop the program till you press the Enter key.


No, not really. Try it yourself. It will stop the program
till you press _something_ and then the Enter key.

- J.
Jan 29 '06 #6
Tom
On Sun, 29 Jan 2006 14:39:45 -0500, "Victor Bazarov"
<v.********@comAcast.net> wrote:
Tom wrote:
On Sun, 29 Jan 2006 08:43:57 -0800, "osmium" <r1********@comcast.net>
wrote:
"Jackie" writes:

I just want the programme to stop for a while.

Your best bet is probably the system() function since
it lets you interact with the OS. For example, in Windows, try
system("pause");


In C type logic ... I create a dummy string and use gets() to pause a
program.

#include <stdio.h>

char junk[81];
printf("routine_name(%d):"
" hit return to continue the paused program ...\n", __LINE__);
gets(junk);

That is a *HUGE* security risk. What if I type more than 80 characters?
I suddely make your program _read my input_ into the memory that wasn't
designated for it.
-----------------

gets(junk); is good [..]


No! It's _awful_. Never use it. NEVER!

V


Victor --

I believe you missed the "erroneous" part of the discussion?
The method I proposed is one I have used for years and was learned
from a C textbook. Typically I set the size of junk[] to 240
characters and use it for all types of input and output. But how do
you justify that size without other usages?

Check out the Microsoft help on gets(). You will see they use a size
of 81 for that example.

If you "get" 80 characters from a erroneous pool of xxxx characters
.... what remains is (xxxx - 80) erroneous characters. I suppose those
erroneous characters are a *HUGE* security risk and they are _awful_
too. Perhaps we should destroy all computers ... the risk is just
great for mankind.

I took the effort to read several of your replies. Your knowledge of
C++ is light years beyond mine as easily observed; however, you seem
to have made yourself a self appointed cop in the group?

And your preferred solution to the original question is .... ???

Please impress me with "how" to do things better and quit slamming
folks for existing outside your definition of intelligence. Go ahead,
teach me! I can learn from you. And just maybe ... you can learn a
thing or two as well?

-- Tom
Jan 29 '06 #7
Tom wrote:
On Sun, 29 Jan 2006 14:39:45 -0500, "Victor Bazarov"
<v.********@comAcast.net> wrote:
Tom wrote:
On Sun, 29 Jan 2006 08:43:57 -0800, "osmium" <r1********@comcast.net>
wrote:

"Jackie" writes:

> I just want the programme to stop for a while.
Your best bet is probably the system() function since
it lets you interact with the OS. For example, in Windows, try
system("pause");

In C type logic ... I create a dummy string and use gets() to pause a
program.

#include <stdio.h>

char junk[81];
printf("routine_name(%d):"
" hit return to continue the paused program ...\n", __LINE__);
gets(junk);


That is a *HUGE* security risk. What if I type more than 80 characters?
I suddely make your program _read my input_ into the memory that wasn't
designated for it.
-----------------

gets(junk); is good [..]

No! It's _awful_. Never use it. NEVER!

V


Victor --

I believe you missed the "erroneous" part of the discussion?
The method I proposed is one I have used for years and was learned
from a C textbook. Typically I set the size of junk[] to 240
characters and use it for all types of input and output. But how do
you justify that size without other usages?

Check out the Microsoft help on gets(). You will see they use a size
of 81 for that example.

If you "get" 80 characters from a erroneous pool of xxxx characters
... what remains is (xxxx - 80) erroneous characters. I suppose those
erroneous characters are a *HUGE* security risk and they are _awful_
too. Perhaps we should destroy all computers ... the risk is just
great for mankind.

I took the effort to read several of your replies. Your knowledge of
C++ is light years beyond mine as easily observed; however, you seem
to have made yourself a self appointed cop in the group?

And your preferred solution to the original question is .... ???

Please impress me with "how" to do things better and quit slamming
folks for existing outside your definition of intelligence. Go ahead,
teach me! I can learn from you. And just maybe ... you can learn a
thing or two as well?

-- Tom


For what its worth, I second this.
V - take a few deep breaths before you fire off next time. Proficiency
in C++ does not entitle you to bad manners.
--dakka
Jan 29 '06 #8
Tom wrote:
On Sun, 29 Jan 2006 14:39:45 -0500, "Victor Bazarov"
<v.********@comAcast.net> wrote:
Tom wrote:
char junk[81];
printf("routine_name(%d):"
" hit return to continue the paused program ...\n", __LINE__);
gets(junk);
That is a *HUGE* security risk. What if I type more than 80 characters?
I suddely make your program _read my input_ into the memory that wasn't
designated for it.


I believe you missed the "erroneous" part of the discussion?


No, you just missed the point. He's right, it's an enormous security
risk and it's awful. You need to spend less time being defensive and
more time worrying about writing correct code.
The method I proposed is one I have used for years and was learned
from a C textbook.
Marvelous. It's wrong.
If you "get" 80 characters from a erroneous pool of xxxx characters
... what remains is (xxxx - 80) erroneous characters. I suppose those
erroneous characters are a *HUGE* security risk and they are _awful_
too. Perhaps we should destroy all computers ... the risk is just
great for mankind.
Uh, are you seriously not familiar with the concept of a buffer
overflow? You allocate an array of 80 characters, then pass that array
(as a pointer) to a function which will read in as many characters as
the user cares to type. The 81st character clobbers some random chunk
of memory, and you get undefined behavior; in many cases, this is an
easy security exploit.
I took the effort to read several of your replies. Your knowledge of
C++ is light years beyond mine as easily observed; however, you seem
to have made yourself a self appointed cop in the group?
Warning people not to heed dangerous and incorrect advice is a good
thing. Why is this personal for you?
Please impress me with "how" to do things better and quit slamming
folks for existing outside your definition of intelligence.
Nobody slammed you. The dangerous and ill-founded recommendation you
voiced received a well-deserved thrashing, but that, again, is a good
thing.
Go ahead,
teach me! I can learn from you. And just maybe ... you can learn a
thing or two as well?


Enough melodrama. This is a technical newsgroup, please make sound
technical arguments. Nobody's convinced of anything by hissy fits.

Luke

Jan 29 '06 #9
"Jacek Dziedzic" <jacek@no_spam.tygrys.no_spam.net> wrote in message
news:56***************************@news.chello.pl. ..
Alvin wrote:
Jackie wrote:

I just want the programme to stop for a while.
Thanks.

Do you want the program to stop until you hit enter? If so, use cin like:

string str;
cin >> str;

That will stop the program till you press the Enter key.


No, not really. Try it yourself. It will stop the program
till you press _something_ and then the Enter key.

- J.


This is what I also use, std::cin >> str;
but if you are not worried about platform compatability you could use
whatever your compiler allows to see if a key has been pressed. I know that
microsoft compilers generally have a kbhit used like:
while ( !kbhit() );

I've always wished this to be part of the standard cause it's just so
useful.
Jan 29 '06 #10
On Sun, 29 Jan 2006 20:23:57 GMT, Tom <Th********@earthlink.net>
wrote:
On Sun, 29 Jan 2006 14:39:45 -0500, "Victor Bazarov"
<v.********@comAcast.net> wrote:
Tom wrote:
On Sun, 29 Jan 2006 08:43:57 -0800, "osmium" <r1********@comcast.net>
wrote:

"Jackie" writes:

> I just want the programme to stop for a while.

Your best bet is probably the system() function since
it lets you interact with the OS. For example, in Windows, try
system("pause");
In C type logic ... I create a dummy string and use gets() to pause a
program.

#include <stdio.h>

char junk[81];
printf("routine_name(%d):"
" hit return to continue the paused program ...\n", __LINE__);
gets(junk);
That is a *HUGE* security risk. What if I type more than 80 characters?
I suddely make your program _read my input_ into the memory that wasn't
designated for it.
-----------------

gets(junk); is good [..]


No! It's _awful_. Never use it. NEVER!

V


Victor --

I believe you missed the "erroneous" part of the discussion?
The method I proposed is one I have used for years and was learned
from a C textbook.


Wow, you've been programming for years and you STILL write code this
bad?
Typically I set the size of junk[] to 240
characters and use it for all types of input and output. But how do
you justify that size without other usages?

Check out the Microsoft help on gets(). You will see they use a size
of 81 for that example.


You will also see this comment on the line using gets:

// Danger: No way to limit input to 20 chars.
// Much preferable: fgets( line, 21, stdin );
// but you'd have to remove the trailing '\n'

If you make a habit of this sort of thing, please consider not giving
people advice.
Jan 29 '06 #11
Jacek Dziedzic wrote:
No, not really. Try it yourself. It will stop the program
till you press something and then the Enter key.

- J.


In that case, getc() or getchar() will do the trick, but that's isn't C++.
That's why I suggested the cin way instead. :)

Alvin
Jan 29 '06 #12
On Sun, 29 Jan 2006 18:55:55 GMT, Tom <Th********@earthlink.net> wrote
in comp.lang.c++:
On Sun, 29 Jan 2006 08:43:57 -0800, "osmium" <r1********@comcast.net>
wrote:
"Jackie" writes:
I just want the programme to stop for a while.


Your best bet is probably the system() function since
it lets you interact with the OS. For example, in Windows, try
system("pause");


In C type logic ... I create a dummy string and use gets() to pause a
program.

#include <stdio.h>

char junk[81];
printf("routine_name(%d):"
" hit return to continue the paused program ...\n", __LINE__);
gets(junk);

-----------------

gets(junk); is good


[snip]

No, gets() is bad. It is the only function in the entire C and C++
standard libraries that is impossible to use safely.

See specifically: http://c-faq.com/stdio/getsvsfgets.html

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://c-faq.com/
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~a...FAQ-acllc.html
Jan 30 '06 #13
Tom
On 29 Jan 2006 13:21:18 -0800, "Luke Meyers" <n.***********@gmail.com>
wrote:
Tom wrote:
On Sun, 29 Jan 2006 14:39:45 -0500, "Victor Bazarov"
<v.********@comAcast.net> wrote:
>Tom wrote:
>> char junk[81];
>> printf("routine_name(%d):"
>> " hit return to continue the paused program ...\n", __LINE__);
>> gets(junk);
>
>That is a *HUGE* security risk. What if I type more than 80 characters?
>I suddely make your program _read my input_ into the memory that wasn't
>designated for it.


I believe you missed the "erroneous" part of the discussion?


No, you just missed the point. He's right, it's an enormous security
risk and it's awful. You need to spend less time being defensive and
more time worrying about writing correct code.
The method I proposed is one I have used for years and was learned
from a C textbook.


Marvelous. It's wrong.
If you "get" 80 characters from a erroneous pool of xxxx characters
... what remains is (xxxx - 80) erroneous characters. I suppose those
erroneous characters are a *HUGE* security risk and they are _awful_
too. Perhaps we should destroy all computers ... the risk is just
great for mankind.


Uh, are you seriously not familiar with the concept of a buffer
overflow? You allocate an array of 80 characters, then pass that array
(as a pointer) to a function which will read in as many characters as
the user cares to type. The 81st character clobbers some random chunk
of memory, and you get undefined behavior; in many cases, this is an
easy security exploit.
I took the effort to read several of your replies. Your knowledge of
C++ is light years beyond mine as easily observed; however, you seem
to have made yourself a self appointed cop in the group?


Warning people not to heed dangerous and incorrect advice is a good
thing. Why is this personal for you?
Please impress me with "how" to do things better and quit slamming
folks for existing outside your definition of intelligence.


Nobody slammed you. The dangerous and ill-founded recommendation you
voiced received a well-deserved thrashing, but that, again, is a good
thing.
Go ahead,
teach me! I can learn from you. And just maybe ... you can learn a
thing or two as well?


Enough melodrama. This is a technical newsgroup, please make sound
technical arguments. Nobody's convinced of anything by hissy fits.

Luke

Bravo !!

I stand corrected. Although I have never experienced (knowingly) the
buffer overflow problem (I guess I seldom fall asleep into the
keyboard) ... it is a possible problem. Here's some proof >>

#include <stdio.h>

void main(int argc, char* argv[])
{
char junk[6];
printf("enter 10 characters and hit return\n");
gets(junk);
printf("junk = %s\n");
}

-----------

Keyboard Input >> 1234567890

Output >>

junk = 1234567890

AND the following crash:

Run-Time Check Failure #2 - Stack around the variable 'junk' was
corrupted.

-----------

Very interesting how characters 67890 were read into memory not
assigned. Certainly overwriting memory that had not been allocated.

Here's a proposed solution that allows plenty of bogus key taps.

-----------------
#include <stdio.h>
#include <ctype.h>

void main(int argc, char* argv[])
{
char alpha, junk[81];
printf("enter erroneous garbage if you like ..."
" return key continues program.\n");
if(isalpha(alpha = getchar()))
{
while(isalpha(alpha = getchar()));
gets(junk);
}
printf("\nreturn key was entered.\n"
"main(%d): program now paused ...\n", __LINE__);
gets(junk);
printf("... program continues\n");
}

-----------------
Note the need for two "gets(junk);"
The first acts only if there are erroneous characters present.
This is a mess!! But it seems to work.

And now ...

How about a Guru's C++ style solution for pausing with/without
erroneous garbage in the input buffer?

-- Tom
Jan 30 '06 #14
Alvin wrote:
Jackie wrote:
I just want the programme to stop for a while.
Thanks.


Do you want the program to stop until you hit enter? If so, use cin like:

string str;
cin >> str;


The problem is if the operator types something like "hello world". Then
cin >> str will read "hello", but leave the "world" out there.

Better would be:

std::string str;
std::getline(cin,str);

Jan 30 '06 #15
Alvin wrote:
Jacek Dziedzic wrote:

No, not really. Try it yourself. It will stop the program
till you press something and then the Enter key.

- J.

In that case, getc() or getchar() will do the trick, but that's isn't C++.
That's why I suggested the cin way instead. :)


Yes, I get it. I pause in the same way. I was only being
picky about the fact that it does not, in fact, wait for
the Enter key but for a string and then the Enter key.

cheers,
- J.
Jan 30 '06 #16
> And now ...

How about a Guru's C++ style solution for pausing with/without
erroneous garbage in the input buffer?


std::string junk;
std::cin >> junk;

Jan 30 '06 #17
Marcin Kalicinski wrote:
And now ...

How about a Guru's C++ style solution for pausing with/without
erroneous garbage in the input buffer?


std::string junk;
std::cin >> junk;


So what happens when "hello world is entered"? Some other solutions
presented so far are much better.

I've been amazed at how many answers betray a fundamental lack of
knowledge about C++ (and C) I/O.

Brian


Jan 30 '06 #18
red floyd <no*****@here.dude> wrote:
The problem is if the operator types something like "hello world". Then
cin >> str will read "hello", but leave the "world" out there.

Better would be:

std::string str;
std::getline(cin,str);


I second this suggestion. Also, it seems not to require the user to
type anything other than the carriage return, plus it avoids the buffer
overrun issue.

[Slightly OT]
I have used this technique in several of my programs that are
command-line driven in Windows: if the user mistakenly double-clicks the
program to run it, I can display a usage message without the command
prompt box disappearing immediately, using only standard facilities.
[/OT]

--
Marcus Kwok
Jan 30 '06 #19
Neo
"Jackie" <Sh***************@gmail.com> wrote in
news:11*********************@f14g2000cwb.googlegro ups.com:
I just want the programme to stop for a while.
Thanks.


gee.. he just wanted the program to synchonously stop for a while with or
without user interruption.

If ur using turbo c++ .. there is a function in #include<dos.h> called..
delay(int millisec);

Should be what ur looking for. I'm not sure if its in the c++ std.

Nice day
Jan 31 '06 #20
Neo wrote:
"Jackie" <Sh***************@gmail.com> wrote in
news:11*********************@f14g2000cwb.googlegro ups.com:
If ur using turbo c++ .. there is a function in #include<dos.h> called..
delay(int millisec);

Should be what ur looking for. I'm not sure if its in the c++ std.


I think it's not too surprising that <dos.h> is not in the C++
standard.

I suggest using the Boost Timer library.

Luke

Jan 31 '06 #21
Tom
(Marcus Kwok) wrote:

[snip]
Better would be:

std::string str;
std::getline(cin,str);


I second this suggestion. Also, it seems not to require the user to
type anything other than the carriage return, plus it avoids the buffer
overrun issue.


The above solution rocks !!

I had not yet used STL (Standard Template Library)
and did a little digging to understand it more fully.

Wow! Another door opens. Using the size function (see below) certainly
convinced me that the above method is very good indeed.

#include <string>
#include <iostream>

void main( )
{
using namespace std;
cout << "input a line of text" << endl;
std::string str;
std::getline(cin,str);
cout << "str: " << str << endl;
cout << "str size: " << (int)str.size() << endl;
}

Type: >return< yields: str size: 0
Type: "Hello World.">return< yields: str size: 12

I also observed that in the Original C++ FAQs that Cline/Lomow took
the effort in FAQ #459 to list a header file for utilizing strings.
This header file resizes the string variable as needed. The header
file is approximately 49 lines of code. Not a trivial task in my
opinion.

There are some other useful functions with the string STL and tons of
other STL's as well. I am tempted to start a thread asking which STL's
people find the most useful. Fact is, I need an education on C++
libraries in general. Guess I'll just lurk a bit and do some more
digging on my own.

==========================

Also, the following MS example demonstrates an easy way to "pause" a
program momentarily. (Versus stop it till you hit return.)

// effects_buffering.cpp
// compile with: EHsc
#include <iostream>
#include <time.h>
using namespace std;

void main( )
{
time_t tm = time( NULL ) + 5;
cout << "Please wait..." << flush;
while ( time( NULL ) < tm )
;
cout << "\nAll done" << endl;
}
--------------
-- Tom
Jan 31 '06 #22

Tom wrote:
#include <string>
#include <iostream>

void main( )
{
using namespace std;
cout << "input a line of text" << endl;
std::string str;
std::getline(cin,str);
cout << "str: " << str << endl;
cout << "str size: " << (int)str.size() << endl;
}


No need to cast the result of size() to an int. It will work perfectly
well without the cast. Since casts should be avoided whenever possible,
best to get rid of it. Also, prefer C++ style casts to C style casts.
They are generally safer and, importantly, much more obvious to a human
reader.

Gavin Deane

Jan 31 '06 #23

Tom wrote:

[snip]
#include <string>
#include <iostream>

void main( )
It should be *int main()*

{
using namespace std;
cout << "input a line of text" << endl;
std::string str;
std::getline(cin,str);
cout << "str: " << str << endl;
cout << "str size: " << (int)str.size() << endl;
}


[snip]

HTH,

Marcelo Pinto

Jan 31 '06 #24
Tom
On 31 Jan 2006 04:35:51 -0800, "Marcelo Pinto" <mp******@gmail.com>
wrote:
[snip]
#include <string>
#include <iostream>

void main( )


It should be *int main()*


Please explain why.

I noticed several MS examples of use: void main( )
I've read somewhere that main should return a value, but I thought
that requirement was no longer necessary. The compiler complains
without a return value when the int return is specified ... but the
usage of void produced no errors on compilation or execution.

Thanks.

-- Tom
Jan 31 '06 #25

"Tom" <Th********@earthlink.net> wrote in message
news:b7********************************@4ax.com...
I noticed several MS examples of use: void main( )
I've read somewhere that main should return a value, but I thought
that requirement was no longer necessary. The compiler complains
without a return value when the int return is specified ... but the
usage of void produced no errors on compilation or execution.

Please see:
http://www.parashift.com/c++-faq-lit....html#faq-29.3

Regards,
Sumit.
--
Sumit Rajan <su****@msdc.hcltech.com>
Jan 31 '06 #26
Tom
On 31 Jan 2006 02:46:45 -0800, "Gavin Deane" <de*********@hotmail.com>
wrote:

Tom wrote:
#include <string>
#include <iostream>

void main( )
{
using namespace std;
cout << "input a line of text" << endl;
std::string str;
std::getline(cin,str);
cout << "str: " << str << endl;
cout << "str size: " << (int)str.size() << endl;
}


No need to cast the result of size() to an int. It will work perfectly
well without the cast. Since casts should be avoided whenever possible,
best to get rid of it. Also, prefer C++ style casts to C style casts.
They are generally safer and, importantly, much more obvious to a human
reader.

Gavin Deane


Thanks for the advice. Without the cast the compiler issued a warning
and I usually aim for zero warnings. Please give me an example of the
preferred cast style. My guess is:

cout << "str size: " << static_cast<int>str.size() << endl;

Given the choice of a compilation warning or making a cast ... what
guidelines should be considered?

-- Tom

Jan 31 '06 #27

Tom wrote:
On 31 Jan 2006 02:46:45 -0800, "Gavin Deane" <de*********@hotmail.com>
wrote:

Tom wrote:
#include <string>
#include <iostream>

void main( )
{
using namespace std;
cout << "input a line of text" << endl;
std::string str;
std::getline(cin,str);
cout << "str: " << str << endl;
cout << "str size: " << (int)str.size() << endl;
}
No need to cast the result of size() to an int. It will work perfectly
well without the cast. Since casts should be avoided whenever possible,
best to get rid of it. Also, prefer C++ style casts to C style casts.
They are generally safer and, importantly, much more obvious to a human
reader.

Gavin Deane


Thanks for the advice. Without the cast the compiler issued a warning
and I usually aim for zero warnings.


Good decision IMO.
Please give me an example of the
preferred cast style. My guess is:

cout << "str size: " << static_cast<int>str.size() << endl;
Nearly. The syntax is static_cast<type>(expression) so you just need to
add parentheses

static_cast<int>(str.size() )

I'm surprised you got a warning though. string::size_type will be some
integral type and cout should know what to do with them.
Given the choice of a compilation warning or making a cast ... what
guidelines should be considered?


Well, I always try and compile with the warning level as high as
possible and warnings treated as errors. Code with warnings fails to
compile so the choice I have is not "accept the warning or cast it
away", it is "use a cast or re-examine my design".

If I know exactly what the compiler is warning about and exactly why,
and I am happy that I really do know best, then a cast it is. For
example, sometimes I really do want to truncate a floating point number
and just remember the integer part. In which case

int i = static_cast<int>(double_value);

does what I want.

If the warning surprises me in any way because I thought what I was
doing was OK, then I will take another look at the code to see what I
might have got wrong.

Gavin Deane

Jan 31 '06 #28

Tom escreveu:
On 31 Jan 2006 04:35:51 -0800, "Marcelo Pinto" <mp******@gmail.com>
wrote:
[snip]
#include <string>
#include <iostream>

void main( )


It should be *int main()*


Please explain why.

I noticed several MS examples of use: void main( )
I've read somewhere that main should return a value, but I thought
that requirement was no longer necessary. The compiler complains
without a return value when the int return is specified ... but the
usage of void produced no errors on compilation or execution.

Thanks.

-- Tom


The C++ Standard (3.6.1) says that there are two forms of a conforming
main function:

int main() { /* ... */ }

and

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

other forms are implementation specific.

Furthermore, note that there is no need for a return statement in main,
as the implementation shall provide a _return 0;_ if no return
statement is encountered at the end of the main function.

I don't know your compiler, but I believe there are switches that you
can turn on/off in order to get conforming messages and the "automatic"
_return 0;_ in the main function.
HTH,

Marcelo Pinto

Jan 31 '06 #29
In message <11*********************@g44g2000cwa.googlegroups. com>, Gavin
Deane <de*********@hotmail.com> writes

Tom wrote:
On 31 Jan 2006 02:46:45 -0800, "Gavin Deane" <de*********@hotmail.com>
wrote:
>
>Tom wrote:
>> #include <string>
>> #include <iostream>
>>
>> void main( )
>> {
>> using namespace std;
>> cout << "input a line of text" << endl;
>> std::string str;
>> std::getline(cin,str);
>> cout << "str: " << str << endl;
>> cout << "str size: " << (int)str.size() << endl;
>> }
>
>No need to cast the result of size() to an int. It will work perfectly
>well without the cast. Since casts should be avoided whenever possible,
>best to get rid of it. Also, prefer C++ style casts to C style casts.
>They are generally safer and, importantly, much more obvious to a human
>reader.
>
>Gavin Deane


Thanks for the advice. Without the cast the compiler issued a warning
and I usually aim for zero warnings.


Good decision IMO.
Please give me an example of the
preferred cast style. My guess is:

cout << "str size: " << static_cast<int>str.size() << endl;


Nearly. The syntax is static_cast<type>(expression) so you just need to
add parentheses

static_cast<int>(str.size() )

I'm surprised you got a warning though. string::size_type will be some
integral type and cout should know what to do with them.


The fact that it doesn't should ring alarm bells. Strictly speaking, the
overloads for operator<< for the basic integral types are declared in
<ostream>. I'd be inclined to try including that header before patching
the problem with casts.

--
Richard Herring
Jan 31 '06 #30

Richard Herring wrote:
In message <11*********************@g44g2000cwa.googlegroups. com>, Gavin
Deane <de*********@hotmail.com> writes

Tom wrote:
On 31 Jan 2006 02:46:45 -0800, "Gavin Deane" <de*********@hotmail.com>
wrote:

>
>Tom wrote:
Please give me an example of the
preferred cast style. My guess is:

cout << "str size: " << static_cast<int>str.size() << endl;


Nearly. The syntax is static_cast<type>(expression) so you just need to
add parentheses

static_cast<int>(str.size() )

I'm surprised you got a warning though. string::size_type will be some
integral type and cout should know what to do with them.


The fact that it doesn't should ring alarm bells. Strictly speaking, the
overloads for operator<< for the basic integral types are declared in
<ostream>. I'd be inclined to try including that header before patching
the problem with casts.


Yes. My intention was just to show the correct syntax for using the
cast. But it could read like I was still recommending the cast.

This is exactly the kind of situation I was thinking of when I wrote

<quote>
If the warning surprises me in any way because I thought what I was
doing was OK, then I will take another look at the code to see what I
might have got wrong.
</quote>

in my previous message, but I didn't link that comment very well to the
code.

Thanks for pointing that out. Hope I've been clearer this time.

Gavin Deane

Jan 31 '06 #31
Tom
On Tue, 31 Jan 2006 15:17:42 +0000, Richard Herring <ju**@[127.0.0.1]>
wrote:
[snip]
The fact that it doesn't should ring alarm bells. Strictly speaking, the
overloads for operator<< for the basic integral types are declared in
<ostream>. I'd be inclined to try including that header before patching
the problem with casts.


The above suggestion is excellent and I learned some more digging
around in it's implementation.

I really like the idea of getting away from the undesirable cast and
the impact it has on the readability of the program; however, the
problem did not disappear as hoped.
=====================================
#include <string>
#include <iostream>
#include <ostream>

void main( )
{
using namespace std;
cout << "the program is now paused ... ";
cout << "any erroneous typing will be discarded" << endl;
cout << "type away if you like and ";
cout << "hit return when ready to continue." << endl;
std::string str;
std::getline(cin,str);
cout << "str: " << str << endl;
cout << "str size: " << static_cast<int>(str.size());
cout << "\n" << flush;
}
=====================================

The addition of:

#include <ostream>

Still generates the warning of a size_t to int for the str.size()
function.

The C++ style:

static_cast<int>(str.size())

works without any warnings.

I see <ostream> defines "flush". Earlier I had problems using "flush"
and resorted to using "endl". Now flush works as advertised. An F1
help with ostream selected shows several Str and char type overloads
for operator<<. No overloads to be found for types: int, double,
size_t, etc. within <ostream>.

My guess is another header is needed and then the cast can disappear?

This newbie hasn't yet found the right header.

====================================

I appreciate the earlier suggestion to use:

int main()

And the kind reference to the electronic FAQs that deals with this
specific issue. I dug around for my "read somewhere" memory and found
it in none other than the Cline/Lomow original text on p.#5, FAQ #10
which states:

"We allow the compiler to supply an implicit int return type for
main(); all other functions have an explicit return type. Also, we
exploit the new C++ feature that requires the compiler to insert an
implicit return 0; at end of main()."

The examples within the original text use:

main() // without int return type.

I need to conform wherever possible for best communication and am
confused now on which is the best practice on such a simple issue. The
MS examples are also without the int return type. The electronic FAQs
is more dated, but more available to the masses.

Perhaps those using various compilers can advise if there is a
portability issue?

Maybe it is a case where both are equally right? They do both work on
the compiler I am using. But lean, clean, and fresh is sure a nice
thing.

-- Tom
Feb 1 '06 #32
"Tom" <Th********@earthlink.net> wrote in message
news:mg********************************@4ax.com...
"We allow the compiler to supply an implicit int return type for
main(); all other functions have an explicit return type. Also, we
exploit the new C++ feature that requires the compiler to insert an
implicit return 0; at end of main()."

The examples within the original text use:

main() // without int return type.

I need to conform wherever possible for best communication and am
confused now on which is the best practice on such a simple issue. The
MS examples are also without the int return type. The electronic FAQs
is more dated, but more available to the masses.

Perhaps those using various compilers can advise if there is a
portability issue?

Maybe it is a case where both are equally right? They do both work on
the compiler I am using. But lean, clean, and fresh is sure a nice
thing.


A function without a return value defaults to an int. I'm not sure of the
specifics as to if it works for methods or not, etc..

so, even though
main()
is correct, that it will be compiled to int main()
int main()
is still more correct and should be used. In fact anytime you post any code
in newsgroups dealing with C++ and you show a main function, if it's not
int main()
someone will tell you to fix it.
Feb 1 '06 #33
In message <CH**************@fe04.lga>, Jim Langston
<ta*******@rocketmail.com> writes
"Tom" <Th********@earthlink.net> wrote in message
news:mg********************************@4ax.com.. .
"We allow the compiler to supply an implicit int return type for
main(); all other functions have an explicit return type. Also, we
exploit the new C++ feature that requires the compiler to insert an
implicit return 0; at end of main()."

The examples within the original text use:

main() // without int return type.

I need to conform wherever possible for best communication and am
confused now on which is the best practice on such a simple issue. The
MS examples are also without the int return type. The electronic FAQs
is more dated, but more available to the masses.

Perhaps those using various compilers can advise if there is a
portability issue?

Maybe it is a case where both are equally right? They do both work on
the compiler I am using. But lean, clean, and fresh is sure a nice
thing.


A function without a return value defaults to an int.


In C, but not C++.

--
Richard Herring
Feb 1 '06 #34

Tom wrote:
The examples within the original text use:

main() // without int return type.

I need to conform wherever possible for best communication and am
confused now on which is the best practice on such a simple issue. The
MS examples are also without the int return type. The electronic FAQs
is more dated, but more available to the masses.

Perhaps those using various compilers can advise if there is a
portability issue?

Maybe it is a case where both are equally right? They do both work on
the compiler I am using. But lean, clean, and fresh is sure a nice
thing.


The C++ standard is very clear. main must have return type int. Any
other return type is wrong and so not portable. implicit int has never
been correct standard C++ so main() with no return type is also wrong
and not portable.

Gavin Deane

Feb 1 '06 #35
In message <mg********************************@4ax.com>, Tom
<Th********@earthlink.net> writes
I appreciate the earlier suggestion to use:

int main()

And the kind reference to the electronic FAQs that deals with this
specific issue. I dug around for my "read somewhere" memory and found
it in none other than the Cline/Lomow original text on p.#5, FAQ #10
which states:
That must be an ancient copy. The current FAQ on the subject of int
main() is here:

http://www.parashift.com/c++-faq-lit....html#faq-29.3
"We allow the compiler to supply an implicit int return type for
main();
No such feature in standard C++.
all other functions have an explicit return type. Also, we
exploit the new C++ feature that requires the compiler to insert an
implicit return 0; at end of main()."
But that's OK.

The examples within the original text use:

main() // without int return type.

I need to conform wherever possible for best communication and am
confused now on which is the best practice on such a simple issue.
That's obvious. Follow the Standard.

3.6.1/2: [...] It shall have a return type of type int, but otherwise
its type is implementation-defined. All implementations shall allow both
of the following definitions of main:

int main() { /* ... */ }
and
int main(itn argc, char * argv[]) { /* ... */ }
IOW, it's never wrong (in C++ or C) to use int main()
The
MS examples are also without the int return type. The electronic FAQs
is more dated, but more available to the masses.

Perhaps those using various compilers can advise if there is a
portability issue?

Maybe it is a case where both are equally right?
Depends what you mean by "right". Compliant with the ISO standard, or
compliant with the implementation-specific extensions of a particular
compiler?
They do both work on
the compiler I am using. But lean, clean, and fresh is sure a nice
thing.


--
Richard Herring
Feb 1 '06 #36
In message <mg********************************@4ax.com>, Tom
<Th********@earthlink.net> writes

The addition of:

#include <ostream>

Still generates the warning of a size_t to int for the str.size()
function.

The C++ style:

static_cast<int>(str.size())

works without any warnings.

I see <ostream> defines "flush". Earlier I had problems using "flush"
and resorted to using "endl". Now flush works as advertised. An F1
help with ostream selected shows several Str and char type overloads
for operator<<. No overloads to be found for types: int, double,
size_t, etc. within <ostream>.
Not in the help file, perhaps, but are they actually in the header file
itself? In a compliant implementation there should be overloads for all
the built-in integral and floating-point types. (size_t is just a
typedef for one of the built-in types.)

Oh, and these overloads for the basic types are member functions of
basic_ostream, whereas overloads for strings etc may be non-member free
functions, so they may be in a different section of your documentation.

My guess is another header is needed and then the cast can disappear?

This newbie hasn't yet found the right header.


Or the right compiler?

--
Richard Herring
Feb 1 '06 #37

Jim Langston wrote:

[snip]
A function without a return value defaults to an int. I'm not sure of the
specifics as to if it works for methods or not, etc..

[snip]

IIRC, implicit int was depracated in C90. And it is definetely out of
the C99 Standard and of the C++ Standard.

HTH,

Marcelo Pinto.

Feb 1 '06 #38
Richard Herring wrote:
In message <CH**************@fe04.lga>, Jim Langston
<ta*******@rocketmail.com> writes >"Tom" <Th********@earthlink.net>
wrote in message
news:mg********************************@4ax.com... A function without a return value defaults to an int.


In C, but not C++.


And not even in C as of the new standard, although that is spreading
very slowly.


Brian
Feb 1 '06 #39

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Andrew | last post by:
When will .NET have a low-pause-time garbage collector A low-pause-time garbage collector would greatly improve .NET's ability to serve as a platform for soft real-time systems. It doesn't have...
1
by: hplloyd | last post by:
Hi i want my VB.NEt application to run a seperate application from the command line, and then wait until this application has completed before continuing I am currently using ...
2
by: tripyre | last post by:
I recently resolved an issue I had with passing a variable to a call shell command, but now I need it to pause or leave the window open so I can manually close it. Below is my code, and I am not...
6
by: Edd Dawson | last post by:
Hi. I have a strange problem involving the passing of command line arguments to a C program I'm writing. I tried posting this in comp.programming yesterday but someone kindly suggested that I'd...
8
by: Wim | last post by:
My GUI application starts a process (a console program) when the user hits Play. I would like to add an option to pause that process. The code I've added to detect if the user hit pause/unpause...
4
by: Trint Smith | last post by:
I need to pause one second here-| | | Try | <-------------------- conn.Open() Dim sqlInsertCommand2 As New SqlCommand(sqlstr, conn) How can I do that please? thanks,
3
by: =?Utf-8?B?S3VlaXNoaW9uZyBUdQ==?= | last post by:
I have a .NET VC++ program, I want to execute some dos command from the program, e.g. copy some file, and etc. How do I do that?
6
by: abie16 | last post by:
Hello All, I have created a page with timer for the employee. They need to click start and stop button when doing their work. I want to have a pause button so when they going for break or anything...
13
by: MZaza | last post by:
What command can I use to make the program quite after a certain condition? -- Mustafa Zaza
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.