OK, this has got to be a simple one and yet I cannot find the answer
in my textbook.
How can I get a simple pause after an output line, that simply waits
for any key to be pressed to move on?
Basically: "Press any key to continue..."
I beleive that I am looking for is something along the lines of a....
cin.get
but do not know the exact syntax for it.
I know it is so simple.... I can make and call functions with eyes
closed yet this illudes me...
Thanks. 31 14244
"da Vinci" <bl***@blank.com> wrote in message
news:ek********************************@4ax.com... OK, this has got to be a simple one and yet I cannot find the answer in my textbook.
How can I get a simple pause after an output line, that simply waits for any key to be pressed to move on?
Basically: "Press any key to continue..."
You can get almost that. With most systems with keyboards,
input is 'line buffered', so your program doesn't see any
input until the user presses the 'Enter' (aka 'return') key.
This lets one edit the input before submitting it to the
program. Think 'fumble-fingers', and 'backspace key' :-)
So for such systems, you can have a 'Press Enter to continue',
in a few different ways.
You could use cin.get(), but I'd only use that as a prelude
to the program's termination, since even though 'get()' only
extracts a single character, the user could easily type in
e.g. ten characters (or more), and those characters would
still be waiting in a 'buffer', and be presented to the
next input request. So you'd need extra code to discard them.
(cin.ignore() etc.)
I find the most useful general purpose way to do this is
with the (nonmember) 'std::getline()' function, which will
extract all characters up to the first newline character, and
store them in a std::string object. (The newline character itself
is extracted but not stored). Then just throw the string away,
or give it to your cat. :-)
Example:
#include <iostream>
#include <string>
void wait4user()
{
std::string response;
std::cout << "Press Enter to continue";
std::getline(std::cin, response);
}
int main()
{
std::cout << "Hello";
wait4user();
std::cout << "world\n";
wait4user();
return 0;
} I beleive that I am looking for is something along the lines of a....
cin.get
cin.get() would work, but has the disadvantage I cited above. but do not know the exact syntax for it.
That's what books are for. :-) Any good C++ compiler
will also provide documentation for the standard library. I know it is so simple.... I can make and call functions with eyes closed yet this illudes me...
Open your eyes. :-)
HTH,
-Mike
Excellent!
It worked like a charm.
I didnt know that info about the cin.get and having characters in the
buffer. Appreciate that! I bet that will save a great deal of heart
ache in the future.
Aw, come on.... keeping your eyes open during the ride is no fun!! :-)
Thanks again.
On Tue, 30 Sep 2003 22:19:06 GMT, "Mike Wahler"
<mk******@mkwahler.net> wrote: "da Vinci" <bl***@blank.com> wrote in message news:ek********************************@4ax.com.. . OK, this has got to be a simple one and yet I cannot find the answer in my textbook.
How can I get a simple pause after an output line, that simply waits for any key to be pressed to move on?
Basically: "Press any key to continue..."
You can get almost that. With most systems with keyboards, input is 'line buffered', so your program doesn't see any input until the user presses the 'Enter' (aka 'return') key. This lets one edit the input before submitting it to the program. Think 'fumble-fingers', and 'backspace key' :-)
So for such systems, you can have a 'Press Enter to continue', in a few different ways.
You could use cin.get(), but I'd only use that as a prelude to the program's termination, since even though 'get()' only extracts a single character, the user could easily type in e.g. ten characters (or more), and those characters would still be waiting in a 'buffer', and be presented to the next input request. So you'd need extra code to discard them. (cin.ignore() etc.)
I find the most useful general purpose way to do this is with the (nonmember) 'std::getline()' function, which will extract all characters up to the first newline character, and store them in a std::string object. (The newline character itself is extracted but not stored). Then just throw the string away, or give it to your cat. :-)
Example:
#include <iostream> #include <string>
void wait4user() { std::string response; std::cout << "Press Enter to continue"; std::getline(std::cin, response); }
int main() { std::cout << "Hello"; wait4user(); std::cout << "world\n"; wait4user(); return 0; }
I beleive that I am looking for is something along the lines of a....
cin.get
cin.get() would work, but has the disadvantage I cited above.
but do not know the exact syntax for it.
That's what books are for. :-) Any good C++ compiler will also provide documentation for the standard library.
I know it is so simple.... I can make and call functions with eyes closed yet this illudes me...
Open your eyes. :-)
HTH, -Mike
da Vinci wrote: Excellent!
Please don't top-post. Read section 5 of the FAQ for posting guidelines. http://www.parashift.com/c++-faq-lite/
-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
> OK, this has got to be a simple one and yet I cannot find the answer in my textbook.
How can I get a simple pause after an output line, that simply waits for any key to be pressed to move on?
Basically: "Press any key to continue..."
I beleive that I am looking for is something along the lines of a....
cin.get
but do not know the exact syntax for it.
There is no way in standard C++ (which is the topic of this newsgroup)
to do something like that. The closest thing would be
std::string dummy;
std::cin >> dummy;
which will wait for <enter>. If you want to detect a key without <enter>,
you will have to use something from your implementation. For further
informations, please ask in a newsgroup supporting your compiler.
> > OK, this has got to be a simple one and yet I cannot find the answer in my textbook.
How can I get a simple pause after an output line, that simply waits for any key to be pressed to move on?
Basically: "Press any key to continue..."
I beleive that I am looking for is something along the lines of a....
cin.get
but do not know the exact syntax for it.
There is no way in standard C++ (which is the topic of this newsgroup) to do something like that. The closest thing would be
std::string dummy; std::cin >> dummy;
which will wait for <enter>. If you want to detect a key without <enter>, you will have to use something from your implementation. For further informations, please ask in a newsgroup supporting your compiler. http://www.parashift.com/c++-faq-lit...t.html#faq-5.9
Jonathan (pressed send to early)
"Jonathan Mcdougall" <jo***************@DELyahoo.ca> wrote in message
news:5n*********************@weber.videotron.net.. . OK, this has got to be a simple one and yet I cannot find the answer in my textbook.
How can I get a simple pause after an output line, that simply waits for any key to be pressed to move on?
Basically: "Press any key to continue..."
I beleive that I am looking for is something along the lines of a....
cin.get
but do not know the exact syntax for it. There is no way in standard C++ (which is the topic of this newsgroup) to do something like that. The closest thing would be
std::string dummy; std::cin >> dummy;
Warning:
This might be sufficient for some circumstances, but
note that there could be a problem.
If this construct is used in a place before subsequent
input is requested, and if in response to the above,
the user supplies input with embedded whitespace,
e.g. "OK I did", only the "OK" will be extracted,
and "I did" is still there waiting, and will be supplied
to the next input.
Use std::getline() instead. which will wait for <enter>. If you want to detect a key without <enter>, you will have to use something from your implementation. For further informations, please ask in a newsgroup supporting your compiler.
Agreed.
-Mike
"da Vinci" <bl***@blank.com> wrote in message
news:6q********************************@4ax.com... Excellent!
It worked like a charm.
I didnt know that info about the cin.get
Start reading, my friend. :-)
and having characters in the buffer.
Perhaps I was not clear enough, but note that my
remarks about 'buffer' were only a generalization
about 'most systems' you're likely to encounter.
From the program's perspective, this issue is not
limited to just cin.get() but to all input operations.
The reason what I showed works, is that by definition,
std::getline() reads everything on a whole line,
and most systems with keyboards will buffer a line
at a time.
The language itself knows nothing about such operating
system buffers, and only 'sees' one character at a time
(The OS controls and supplies these characters to your
program).
Appreciate that! I bet that will save a great deal of heart ache in the future.
Glad I could help.
BTW please don't top post. If you don't know what I'm
talking about, see the link Kevin provided.
-Mike
On Tue, 30 Sep 2003 23:49:09 GMT, "Mike Wahler"
<mk******@mkwahler.net> wrote: Start reading, my friend. :-)
I tried. :) My textbook isn't very good, IMO, and the Schildt C/C++ SE
reference manual does cover get() and getline(), but not to the point
where I could get what I wanted out of it with my 1 month of C++
experiance. This sure isnt Turbo Pascal. :-)
BTW please don't top post. If you don't know what I'm talking about, see the link Kevin provided.
Had no idea, but now that I read the FAQ link, I will ensure I do not
do it any longer. I must have missed it the first time I read through
it.
Thanks.
>Glad I could help. -Mike
Just in case you wanted to see how I used it, this is the program I
was working on. Way beyond what the assignment required, but I have
always gone above and beyond.
Hopefully I am posting the code right. I read the FAQ portion of it
and hope I get it right. (I hate being the new guy!!) I cut out alot
of the white space to save room. This is not how I format everything
in the code.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
// Declare Functions Here
int Display_Main_Menu (int);
void View_Totals (int, int, int, int, int);
int Check_Number (int);
void Wait ();
void Final_Data (int, int, int, int, int);
int main (int)
{
// Variables for various program functions
int day=1, prod_num, quantity_today=0;
int prod_1=0, prod_2=0, prod_3=0, prod_4=0, prod_5=0;
int main_selection, good_or_bad=1;
// Variables for continue statements
char cont='N';
char day_done = 'N';
while ( day <= 7 )
{
main_selection = Display_Main_Menu (day); // Calls Function
switch (main_selection)
{
case 1: // Input Data - While & Switch Loops
system ("cls"); // Clear Screen Command
cont = 'N'; // Must have to avoid infinite looping!!!
while (cont != 'Y' )
{
while ( good_or_bad != 0 )
{
cout << "\n\n\nEnter product number (1-5): ";
cin >> prod_num;
good_or_bad = Check_Number(prod_num);
} // Ends Inner While
good_or_bad = 1; // Reset it to avoid infinite looping!!!
cout << "Enter quantity sold on day " << day << ": ";
cin >> quantity_today;
cout << "\n\nYou sold " << quantity_today
<< " units of product " << prod_num << ".";
cout << "\nIs this correct (Y/N)?";
cin >> cont;
if ( cont == 'y' ) // Sets upper case letter
cont = 'Y';
} // Ends Middle While
switch (prod_num) // Add Quantity to Product Count
{
case 1:
prod_1 = prod_1 + quantity_today;
break;
case 2:
prod_2 = prod_2 + quantity_today;
break;
case 3:
prod_3 = prod_3 + quantity_today;
break;
case 4:
prod_4 = prod_4 + quantity_today;
break;
case 5:
prod_5 = prod_5 + quantity_today;
break;
} // Ends Inner Switch
break;
case 2: // User Selected "View Totals" - Call Function
View_Totals (prod_1, prod_2, prod_3, prod_4, prod_5);
break;
case 3: // User Wants to Advanced One Day
day++;
break;
case 4: // User Wants to End Input Session
day = 8;
break;
} // Ends Outer Switch
} // Ends While
// Display the final sales report from the data entered.
Final_Data (prod_1, prod_2, prod_3, prod_4, prod_5);
return 0;
} // Ends Main
/*This function will be called to display the main menu
for the user. The variable passed out of this function
tells the *main* what menu the user wishes to access.*/
int Display_Main_Menu (int daynum)
{
int selection;
system ("cls"); // Clear Screen Command
cout << "\n\n\nDay " << daynum;
cout << "\n\n*****MAIN MENU*****";
cout << "\n\n1: Enter Data";
cout << "\n2: View Current Totals";
cout << "\n3: Continue to day " << ( daynum + 1 );
cout << "\n4: End Input Session";
cout << "\n\n\nSelection: ";
cin >> selection;
return selection;
}
/*This function will be called to display the totals currently
on file from previous input. There is no value returned from
this function.*/
void View_Totals(int prod1,int prod2,int prod3,int prod4,int prod5)
{
system ("cls"); // Clear Screen Command
cout << "\n\n\nYour current totals are:" << endl;
cout << "\nProduct 1: " << prod1 << endl;
cout << "Product 2: " << prod2 << endl;
cout << "Product 3: " << prod3 << endl;
cout << "Product 4: " << prod4 << endl;
cout << "Product 5: " << prod5 << endl;
Wait(); // Creates a "Press Enter to continue" statement
}
/* This function determines whether the input product number is
correct. The value must be an integer between 1 and 5. If it is
valid, then a value of 0 is returned. If it is invalid, then a
value of 1 is returned.*/
int Check_Number(int prodnum)
{
int return_this;
switch (prodnum)
{
case 1:
case 2:
case 3:
case 4:
case 5:
return_this = 0;
break;
default:
return_this = 1;
break;
}
return return_this;
}
/* This function will use a string to create a pause until the user
hits the enter key. Any other characters entered will be ignored.*/
void Wait()
{
string response;
cout << "Press Enter to continue";
getline(cin, response);
}
/* This function will have the number of products passed into it.
From this data, it will determine the amount of each product sold
and total gross sales for the week. Then, it will display the data.*/
void Final_Data(int prod1,int prod2,int prod3,int prod4,int prod5)
{
double p1total, p2total, p3total, p4total, p5total, gross;
p1total = (prod1 * 2.98);
p2total = (prod2 * 4.50);
p3total = (prod3 * 9.98);
p4total = (prod4 * 4.49);
p5total = (prod5 * 6.87);
gross = (p1total + p2total + p3total + p4total + p5total);
system ("cls"); // Clear Screen
cout << "\n\n\nYour final sales report for this week is as follows:";
cout << "\n\nProduct Number\tAmount Sold\tTotal Income";
cout << "\n1\t\t" << prod1 << "\t\t" << "$" << p1total;
cout << "\n2\t\t" << prod2 << "\t\t" << "$" << p2total;
cout << "\n3\t\t" << prod3 << "\t\t" << "$" << p3total;
cout << "\n4\t\t" << prod4 << "\t\t" << "$" << p4total;
cout << "\n5\t\t" << prod5 << "\t\t" << "$" << p5total;
cout << "\n\nYour total gross sales for this week is $" << gross
<< "\n\n\n";
}
da Vinci wrote: On Tue, 30 Sep 2003 23:49:09 GMT, "Mike Wahler" <mk******@mkwahler.net> wrote:
Start reading, my friend. :-)
I tried. :) My textbook isn't very good, IMO, and the Schildt C/C++ SE reference manual does cover get() and getline(),
From the alt.comp.lang.learn.c-c++ FAQ
( http://www.faqs.org/faqs/C-faq/learn/):
13: What should I look for when picking a book to learn from?
[...]
Many C and C++ experts recommend against using ANY book written by
a certain Herbert Schildt. To see why, read the answer to question
16. [...]
16: Why do many experts not think very highly of Herbert Schildt's
books?
A good answer to this question could fill a book by itself. While
no book is perfect, Schildt's books, in the opinion of many
gurus, seem to positively aim to mislead learners and encourage
bad habits. Schildt's beautifully clear writing style only makes
things worse by causing many "satisfied" learners to recommend his
books to other learners.
Do take a look at the following scathing articles before deciding
to buy a Schildt text. http://www.lysator.liu.se/c/schildt.html http://herd.plethora.net/~seebs/c/c_tcr.html
The above reviews are admittedly based on two of Schildt's older
books. However, the language they describe has not changed in the
intervening period, and several books written at around the same
time remain highly regarded.
The following humorous post also illustrates the general feeling
towards Schildt and his books. http://www.qnx.com/~glen/deadbeef/2764.html
There is exactly one and ONLY one C book bearing Schildt's name on
its cover that is at all recommended by many C experts - see Q 25.
-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
> Just in case you wanted to see how I used it, this is the program I was working on. Way beyond what the assignment required, but I have always gone above and beyond.
That is how we learn.
Hopefully I am posting the code right. I read the FAQ portion of it and hope I get it right. (I hate being the new guy!!)
:)
I cut out alot of the white space to save room.
Don't! This code is very hard to read. Do not use tabs since some
newsreaders (as mine) remove them, but at least indent by one or
two spaces.
This is not how I format everything in the code.
I hope so, if not, don't tell us your name :)
The program in general is quite cool. A couple of guidelines though :
1) give better names to your variables and functions
2) try to break your code a bit more; a function must have a
representative name. If the name is too general (such as do_this() ),
break it until its name represents exactly what it does.
3) too much comment is like not enough
4) learn about arrays and vectors
5) don't give up!
#include <iostream> #include <iomanip> #include <string>
using namespace std;
// Declare Functions Here
int Display_Main_Menu (int); void View_Totals (int, int, int, int, int); int Check_Number (int); void Wait (); void Final_Data (int, int, int, int, int);
<personal opinion>
take the habit of naming the variables even on declaration,
it makes things clearer for everybody
</personal opinion>
int main (int)
Nope. main() has two allowed forms :
int main()
or
int main(int argc, char **argv)
where the names are optional.
{
// Variables for various program functions
int day=1, prod_num, quantity_today=0; int prod_1=0, prod_2=0, prod_3=0, prod_4=0, prod_5=0; int main_selection, good_or_bad=1;
take the habit of defining one variable per line and
to comment each of them. "various program functions" is not
very clear imo :)
// Variables for continue statements
char cont='N'; char day_done = 'N';
while ( day <= 7 ) {
main_selection = Display_Main_Menu (day); // Calls Function
Display_Main_Menu has a misleading name. It does not
only display, it asks for an option and returns it. Either
rename your function or (preferrably) break it in two.
switch (main_selection) { case 1: // Input Data - While & Switch Loops system ("cls"); // Clear Screen Command
non portable, be careful. A system without 'cls' will do
nothing. On my system, 'cls' from the command prompt formats
the disk without warning. its a good thing I did not run it :)
cont = 'N'; // Must have to avoid infinite looping!!! while (cont != 'Y' ) { while ( good_or_bad != 0 )
a variable named good_or_bad does not inform on its use..
{ cout << "\n\n\nEnter product number (1-5): "; cin >> prod_num; good_or_bad = Check_Number(prod_num); } // Ends Inner While
This kind of comment is useless and only clutters the code.
good_or_bad = 1; // Reset it to avoid infinite looping!!!
cout << "Enter quantity sold on day " << day << ": "; cin >> quantity_today; cout << "\n\nYou sold " << quantity_today << " units of product " << prod_num << "."; cout << "\nIs this correct (Y/N)?"; cin >> cont;
if ( cont == 'y' ) // Sets upper case letter cont = 'Y';
look out std::toupper()
} // Ends Middle While
switch (prod_num) // Add Quantity to Product Count {
case 1: prod_1 = prod_1 + quantity_today; break; case 2: prod_2 = prod_2 + quantity_today; break; case 3: prod_3 = prod_3 + quantity_today; break; case 4: prod_4 = prod_4 + quantity_today; break; case 5: prod_5 = prod_5 + quantity_today; break; } // Ends Inner Switch
mmm.. what about an array or a std::vector here (or even a std::map)?
If you didn't learn about them, that's ok, but know that it would
be a lot simpler.
break;
Make the previous case in a seperate function. case 2: // User Selected "View Totals" - Call Function View_Totals (prod_1, prod_2, prod_3, prod_4, prod_5); break;
case 3: // User Wants to Advanced One Day day++; break;
case 4: // User Wants to End Input Session day = 8; break;
} // Ends Outer Switch
Every case should look like these 3 : calling a function or two,
but that's it. If not, well.. it makes it harder to understand.
} // Ends While
// Display the final sales report from the data entered. Final_Data (prod_1, prod_2, prod_3, prod_4, prod_5);
return 0; } // Ends Main
/*This function will be called to display the main menu for the user. The variable passed out of this function tells the *main* what menu the user wishes to access.*/
int Display_Main_Menu (int daynum) {
int selection;
system ("cls"); // Clear Screen Command
non portable
cout << "\n\n\nDay " << daynum; cout << "\n\n*****MAIN MENU*****"; cout << "\n\n1: Enter Data"; cout << "\n2: View Current Totals"; cout << "\n3: Continue to day " << ( daynum + 1 ); cout << "\n4: End Input Session"; cout << "\n\n\nSelection: ";
Use std::endl instead of \n, which is not guaranteed to work
everywhere.
cin >> selection;
return selection;
}
/*This function will be called to display the totals currently on file from previous input. There is no value returned from this function.*/
void View_Totals(int prod1,int prod2,int prod3,int prod4,int prod5) { system ("cls"); // Clear Screen Command
not portable
cout << "\n\n\nYour current totals are:" << endl; cout << "\nProduct 1: " << prod1 << endl; cout << "Product 2: " << prod2 << endl; cout << "Product 3: " << prod3 << endl; cout << "Product 4: " << prod4 << endl; cout << "Product 5: " << prod5 << endl;
Wait(); // Creates a "Press Enter to continue" statement }
/* This function determines whether the input product number is correct. The value must be an integer between 1 and 5. If it is valid, then a value of 0 is returned. If it is invalid, then a value of 1 is returned.*/
When something can have two values meaning 'ok' or 'bad', use a bool
which can have the values 'true' or 'false' :
bool b = true;
b = false;
int Check_Number(int prodnum) { int return_this;
switch (prodnum) { case 1: case 2: case 3: case 4: case 5:
indicate intentional fall-through with a comment since in some cases,
it may not be clear if it is or not.
return_this = 0; break; default: return_this = 1; break; } return return_this;
What about something like
return (prodnum >= 1) && (prodnum <= 5);
assuming the function returns a bool.
}
/* This function will use a string to create a pause until the user hits the enter key. Any other characters entered will be ignored.*/
void Wait() { string response; cout << "Press Enter to continue"; getline(cin, response); }
/* This function will have the number of products passed into it. From this data, it will determine the amount of each product sold and total gross sales for the week. Then, it will display the data.*/
void Final_Data(int prod1,int prod2,int prod3,int prod4,int prod5) { double p1total, p2total, p3total, p4total, p5total, gross;
p1total = (prod1 * 2.98); p2total = (prod2 * 4.50); p3total = (prod3 * 9.98); p4total = (prod4 * 4.49); p5total = (prod5 * 6.87); gross = (p1total + p2total + p3total + p4total + p5total);
system ("cls"); // Clear Screen
cout << "\n\n\nYour final sales report for this week is as follows:";
cout << "\n\nProduct Number\tAmount Sold\tTotal Income"; cout << "\n1\t\t" << prod1 << "\t\t" << "$" << p1total; cout << "\n2\t\t" << prod2 << "\t\t" << "$" << p2total; cout << "\n3\t\t" << prod3 << "\t\t" << "$" << p3total; cout << "\n4\t\t" << prod4 << "\t\t" << "$" << p4total; cout << "\n5\t\t" << prod5 << "\t\t" << "$" << p5total;
cout << "\n\nYour total gross sales for this week is $" << gross << "\n\n\n"; }
Jonathan
"Jonathan Mcdougall" <jo***************@DELyahoo.ca> wrote in message
news:Yn*********************@wagner.videotron.net. .. cout << "\n\n\nSelection: ";
Use std::endl instead of \n, which is not guaranteed to work everywhere.
Eh?
-Mike
> > > cout << "\n\n\nSelection: "; Use std::endl instead of \n, which is not guaranteed to work everywhere.
Eh?
-Mike
Mmm.. I though \n was not portable, I should have informed myself.
Let me rephrase.
I prefer using std::endl since it is clearer than a bunch of \n.
It is also supposed to flush the buffer, but flushing the buffer
does not necessrily mean that the data is written.
Jonathan
"Kevin Goodsell" <us*********************@neverbox.com> wrote in message
news:Z6*****************@newsread4.news.pas.earthl ink.net... da Vinci wrote: Excellent!
Please don't top-post. Read section 5 of the FAQ for posting guidelines.
http://www.parashift.com/c++-faq-lite/
-Kevin -- My email address is valid, but changes periodically. To contact me please use the address from a recent posting.
What's the "approved" method of marking the text you're responding to when
the corporate-mandated, braindead reader (initials are LN) doesn't do it for
you. I've been using <previous></previous> but that seem hokey.
Posted Via Usenet.com Premium Usenet Newsgroup Services
----------------------------------------------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
---------------------------------------------------------- http://www.usenet.com
"Dick Bridges" <db******@codecomplete.com> wrote in message news:3f**********@Usenet.com...
What's the "approved" method of marking the text you're responding to when the corporate-mandated, braindead reader (initials are LN) doesn't do it for you. I've been using <previous></previous> but that seem hokey.
When you press shift and the period key at the same time it prints a >
character. Do that on each included line. This will also encourage
deleting unnecessary quoted material (less >'s to manually insert).
On Wed, 1 Oct 2003 23:58:05 -0400, "Jonathan Mcdougall"
<jo***************@DELyahoo.ca> wrote: Don't! This code is very hard to read. Do not use tabs since some newsreaders (as mine) remove them, but at least indent by one or two spaces.
OK. Sorry about that. When I copied it into the newsreader program to
post it, it looked very unorginized as the text wraps at a certain
point. I will keep this in mind next time.
The program in general is quite cool. A couple of guidelines though :
Thanks. I've been programming C++ since August and this is the most
complicated I've done yet. I really love this stuff. My only
background is BASIC on a Commodore 64 and Turbo Pascal on a 386. So I
am REALLY liking C++! By the way, the requirement for this program was
to use a single switch. As I said, above and beyond!
1) give better names to your variables and functions
One problem I have in doing so is that the teacher has an issue with
her compiler and lines being longer that 70 characters. So, we are
limited in how long we can have a single line. If you notice, I had to
break a bunch of my "long" output lines in half because of this. When
I first designed the program, wrote the pseudocode, and started
coding, I had long variables with _ in them that were specific.
Unfortunantly, I had gone over the 70 characters on a lot of lines.
So, I ended up nixing parts of the variables (product turned to prod)
ect.
2) try to break your code a bit more; a function must have a representative name. If the name is too general (such as do_this() ), break it until its name represents exactly what it does.
OK, I will keep this in mind. After reading your full post, I am going
to make one or two more functions.
3) too much comment is like not enough
I hate it when things walk a fine line between good and bad! When I
first started, I did not like using comments. Mainly because these
programs are so small and simple. I know they would be needed if I was
working within a group. So I try to make sure to comment a lot or else
I wouldnt put any in! Maybe I am over doing it? :-)
4) learn about arrays and vectors
Very soon! I actually want to use an array for the character input at
certain places. This program will crash if someone enters two or more
characters when it is specifically looking for a Y or N. If the user
mis-keyed and hit NB or something (I did once and that is how I found
the problem) it will lock up the program. If I used an array, then
just looked at the [1] position, if they entered NB, it would only see
the N. I think.... :-)
5) don't give up!
NEVER! :-)
<personal opinion> take the habit of naming the variables even on declaration, it makes things clearer for everybody </personal opinion>
which variables? The ones that are being passed in or the ones that
will be used for the variables coming in?
take the habit of defining one variable per line and to comment each of them. "various program functions" is not very clear imo :)
Does it matter how "long" the code is? I know when it is compiled, it
will be the same size regardless of how much white space you use in
the source. There are no draw backs or professional "no-no's" about
doing things line by line instead of grouping?
Display_Main_Menu has a misleading name. It does not only display, it asks for an option and returns it. Either rename your function or (preferrably) break it in two.
Very good point. Thank you!
non portable, be careful. A system without 'cls' will do nothing. On my system, 'cls' from the command prompt formats the disk without warning. its a good thing I did not run it :)
Is there a portable way to clear a screen without using a mass of endl
or \n's?
look out std::toupper()
I've used the toupper() a few times in other program. I don't know why
I didn't use it here. Thanks for the reminder.
mmm.. what about an array or a std::vector here (or even a std::map)? If you didn't learn about them, that's ok, but know that it would be a lot simpler.
Your speaking Greek again. :-) I am vaguely familiar with Arrays and
plan to tackle them next.
Every case should look like these 3 : calling a function or two, but that's it. If not, well.. it makes it harder to understand.
Very true. The problem I ran into when thinking of what I could put
into functions is that I do not know how to do reference or pointers
yet. According to the professor, without one of those I can only pass
one value out of a function.
When something can have two values meaning 'ok' or 'bad', use a bool which can have the values 'true' or 'false' :
bool b = true; b = false;
So would this be good to use as a continue type statement?
bool continue;
continue = false;
while (continue == false) {
cout << "Do you want to continue(Y/N)?";
cin >> continue;
if (continue == 'Y')
continue = true;
else
continue = false;
}
indicate intentional fall-through with a comment since in some cases, it may not be clear if it is or not.
Excellent advice.
What about something like
return (prodnum >= 1) && (prodnum <= 5);
assuming the function returns a bool.
Interesting. I had't thought of that (obviously!). I will give it a
shot.
Thanks for the ideas and help. This is obviously a tight-knit
community and glad to be apart of it.
> > Please don't top-post. Read section 5 of the FAQ for posting guidelines. http://www.parashift.com/c++-faq-lite/
-Kevin -- My email address is valid, but changes periodically. To contact me please use the address from a recent posting.
What's the "approved" method of marking the text you're responding to when the corporate-mandated, braindead reader (initials are LN) doesn't do it
for you. I've been using <previous></previous> but that seem hokey.
There are none, but people use
|
:
or whatever. Just try to make it clear about who you are responding
to and quote only what you are answering to. Do not mess the quotes
either.
Jonathan
> >3) too much comment is like not enough I hate it when things walk a fine line between good and bad! When I first started, I did not like using comments. Mainly because these programs are so small and simple. I know they would be needed if I was working within a group. So I try to make sure to comment a lot or else I wouldnt put any in! Maybe I am over doing it? :-)
Yeah, things like
while ( good_or_bad != 0 )
{
cout << "\n\n\nEnter product number (1-5): ";
cin >> prod_num;
good_or_bad = Check_Number(prod_num);
} // Ends Inner While
You know, it is _clear_ that the bracket ends this while. Or better : 4) learn about arrays and vectors
Very soon! I actually want to use an array for the character input at certain places. This program will crash if someone enters two or more characters when it is specifically looking for a Y or N. If the user mis-keyed and hit NB or something (I did once and that is how I found the problem) it will lock up the program. If I used an array, then just looked at the [1] position, if they entered NB, it would only see the N. I think.... :-)
5) don't give up!
NEVER! :-)
<personal opinion> take the habit of naming the variables even on declaration, it makes things clearer for everybody </personal opinion>
which variables? The ones that are being passed in or the ones that will be used for the variables coming in?
take the habit of defining one variable per line and to comment each of them. "various program functions" is not very clear imo :)
Does it matter how "long" the code is? I know when it is compiled, it will be the same size regardless of how much white space you use in the source. There are no draw backs or professional "no-no's" about doing things line by line instead of grouping?
Display_Main_Menu has a misleading name. It does not only display, it asks for an option and returns it. Either rename your function or (preferrably) break it in two.
Very good point. Thank you!
non portable, be careful. A system without 'cls' will do nothing. On my system, 'cls' from the command prompt formats the disk without warning. its a good thing I did not run it :)
Is there a portable way to clear a screen without using a mass of endl or \n's?
look out std::toupper()
I've used the toupper() a few times in other program. I don't know why I didn't use it here. Thanks for the reminder.
mmm.. what about an array or a std::vector here (or even a std::map)? If you didn't learn about them, that's ok, but know that it would be a lot simpler.
Your speaking Greek again. :-) I am vaguely familiar with Arrays and plan to tackle them next.
Every case should look like these 3 : calling a function or two, but that's it. If not, well.. it makes it harder to understand.
Very true. The problem I ran into when thinking of what I could put into functions is that I do not know how to do reference or pointers yet. According to the professor, without one of those I can only pass one value out of a function.
When something can have two values meaning 'ok' or 'bad', use a bool which can have the values 'true' or 'false' :
bool b = true; b = false;
So would this be good to use as a continue type statement?
bool continue; continue = false;
while (continue == false) { cout << "Do you want to continue(Y/N)?"; cin >> continue;
if (continue == 'Y') continue = true; else continue = false; }
indicate intentional fall-through with a comment since in some cases, it may not be clear if it is or not.
Excellent advice.
What about something like
return (prodnum >= 1) && (prodnum <= 5);
assuming the function returns a bool.
Interesting. I had't thought of that (obviously!). I will give it a shot.
Thanks for the ideas and help. This is obviously a tight-knit community and glad to be apart of it.
> >3) too much comment is like not enough I hate it when things walk a fine line between good and bad! When I first started, I did not like using comments. Mainly because these programs are so small and simple. I know they would be needed if I was working within a group. So I try to make sure to comment a lot or else I wouldnt put any in! Maybe I am over doing it? :-)
Yeah, things like
while ( good_or_bad != 0 )
{
cout << "\n\n\nEnter product number (1-5): ";
cin >> prod_num;
good_or_bad = Check_Number(prod_num);
} // Ends Inner While
You know, it is _clear_ that the bracket ends this while. Or better :
return 0;
} // Ends Main
This was actually funny :) 4) learn about arrays and vectors
Very soon!
Be careful with them though. I suggest you take a look to std::vector
before arrays, since arrays are error-prone, but I suppose your
teacher knows what she's doing. <personal opinion> take the habit of naming the variables even on declaration, it makes things clearer for everybody </personal opinion> which variables? The ones that are being passed in or the ones that will be used for the variables coming in?
Both (if I understand correctly) :
// variables named
void f(int a, int b);
int main()
{
f(1, 2);
}
// ditto
void f(int a, int b)
{
} take the habit of defining one variable per line and to comment each of them. "various program functions" is not very clear imo :)
Does it matter how "long" the code is? I know when it is compiled, it will be the same size regardless of how much white space you use in the source. There are no draw backs or professional "no-no's" about doing things line by line instead of grouping?
No. Depending on the company standards, you will do things differently,
but for programs like that, try to make it as clear as possible. non portable, be careful. A system without 'cls' will do nothing. On my system, 'cls' from the command prompt formats the disk without warning. its a good thing I did not run it :)
Is there a portable way to clear a screen without using a mass of endl or \n's?
No. C++ can be used in toasters, you know. mmm.. what about an array or a std::vector here (or even a std::map)? If you didn't learn about them, that's ok, but know that it would be a lot simpler.
Your speaking Greek again. :-) I am vaguely familiar with Arrays and plan to tackle them next.
Mmm... if you have a choice, forget arrays right now. http://cplus.about.com/library/weekly/aa050102e.htm
Or have a Google on std::vector. Do not stop on details like
the weird std:: notation. Try to understand the whole.
Post questions here if you don't understand. Every case should look like these 3 : calling a function or two, but that's it. If not, well.. it makes it harder to understand.
Very true. The problem I ran into when thinking of what I could put into functions is that I do not know how to do reference or pointers yet. According to the professor, without one of those I can only pass one value out of a function.
It does not matter whether you pass by reference or by value. But
actually, you are right. It would be a bit more complicated
to seperate that one.
What would be interesting is to keep that program and to work on
it as your knowledge increases, tweaking it and making it look
right. When something can have two values meaning 'ok' or 'bad', use a bool which can have the values 'true' or 'false' :
bool b = true; b = false;
So would this be good to use as a continue type statement?
bool continue; continue = false;
while (continue == false) { cout << "Do you want to continue(Y/N)?"; cin >> continue;
if (continue == 'Y') continue = true; else continue = false; }
Could be, except that you use 'continue' as a char and a boolean,
but you understand. Personaly, something like
do
{
cout << "Do you want to continue(Y/N)?";
cin >> continue;
} while ( std::toupper(continue) != 'Y' );
If you are not familiar with this version of while, you can
stay with the preceeding one, it is quite good. Or try this
while ( true ) // infinit loop
{
cout << "Do you want to continue(Y/N)?";
cin >> continue;
if ( std::toupper(continue) == 'Y' )
break; // exits the loop
}
which gets rid of a variable.
Thanks for the ideas and help. This is obviously a tight-knit community and glad to be apart of it.
Hehe.. depends on the people.
Jonathan
"Jonathan Mcdougall" <jo***************@DELyahoo.ca> wrote in message
news:Ft******************@weber.videotron.net... > cout << "\n\n\nSelection: ";
Use std::endl instead of \n, which is not guaranteed to work everywhere.
Eh?
-Mike
Mmm.. I though \n was not portable, I should have informed myself. Let me rephrase.
I prefer using std::endl since it is clearer than a bunch of \n. It is also supposed to flush the buffer, but flushing the buffer does not necessrily mean that the data is written.
Again, Eh?
-Mike
"da Vinci" <bl***@blank.com> wrote 4) learn about arrays and vectors Very soon! I actually want to use an array for the character input at certain places. This program will crash if someone enters two or more characters when it is specifically looking for a Y or N. If the user mis-keyed and hit NB or something (I did once and that is how I found the problem) it will lock up the program. If I used an array, then just looked at the [1] position, if they entered NB, it would only see the N. I think.... :-)
Use a string, and use getline. You can look at the first position of
a string using the [] indexing operator, but remember the positions
are numbered from zero.
Is there a portable way to clear a screen without using a mass of endl or \n's?
No. mmm.. what about an array or a std::vector here (or even a std::map)? If you didn't learn about them, that's ok, but know that it would be a lot simpler.
Your speaking Greek again. :-) I am vaguely familiar with Arrays and plan to tackle them next.
It's your call, obviously, but vectors are easier to use. Arrays aren't
*very* hard but there are subtleties.
So would this be good to use as a continue type statement?
bool continue; continue = false;
while (continue == false) { cout << "Do you want to continue(Y/N)?"; cin >> continue;
if (continue == 'Y') continue = true; else continue = false; }
No, because `continue' is a keyword. And because 'cin >> x' where x
is a bool expects either 0/1 or true/false or vrai/faux depending on
various factors, but never Y/N. Use a string and use getline. Apart
from that, the principle is sound and you could do:
bool carry_on = false;
while (carry_on == false)
{
std::cout << "Do you want to continue (Y/N)?\n";
std::string response;
std::getline (std::cin, response);
if (response [0] == 'Y') carry_on = true;
else carry_on = false;
// or replace the previous two lines with:
// carry_on = (response [0] == 'Y');
}
What would be simpler, though, is:
while (true)
{
std::cout << "Do you want to continue (Y/N)?\n";
std::string response;
std::getline (std::cin, response);
if (response [0] != 'Y') break;
}
Regards,
Buster. When something can have two values meaning 'ok' or 'bad', use a bool which can have the values 'true' or 'false' :
bool b = true; b = false;
So would this be good to use as a continue type statement?
bool continue; continue = false;
while (continue == false) { cout << "Do you want to continue(Y/N)?"; cin >> continue;
if (continue == 'Y') continue = true; else continue = false; }
Could be, except that you use 'continue' as a char and a boolean, but you understand. Personaly, something like
do { cout << "Do you want to continue(Y/N)?"; cin >> continue;
} while ( std::toupper(continue) != 'Y' );
If you are not familiar with this version of while, you can stay with the preceeding one, it is quite good. Or try this
while ( true ) // infinit loop { cout << "Do you want to continue(Y/N)?"; cin >> continue;
if ( std::toupper(continue) == 'Y' ) break; // exits the loop
Thanks to Buster for reminding me that continue is a keyword,
so it is illegal to use it as a variable name.
Sorry about that,
Jonathan
On Thu, 2 Oct 2003 13:46:29 -0400, "Jonathan Mcdougall"
<jo***************@DELyahoo.ca> wrote: return 0; } // Ends Main
This was actually funny :)
It didn't seem so at the time, but now I do see the humor in it. :)
Be careful with them though. I suggest you take a look to std::vector before arrays, since arrays are error-prone, but I suppose your teacher knows what she's doing.
Actually, I am 2 months ahead in all of my assignments. So I am
basically self teaching myself function use and everything else until
the class catches up. I was personally going to learn arrays next, but
will look at vectors first if that is the better approach. Thing is, I
know the basics of arrays already. I know nothing of vectors except
what I learned in Physics.... but I doubt that is what were talking
about here. :)
Both (if I understand correctly) :
// variables named void f(int a, int b);
int main() { f(1, 2); }
// ditto void f(int a, int b)
OK, I think I see what you mean. Basically, instead of declaring a
function with
int This_Function(int, int, int);
use
int This_Function (int var1, int var2, int var3)
then write the code for the function starting with the same line.
Basically, take the function I am writing, take the first line of it,
and post that at the top of the code as well?
No. Depending on the company standards, you will do things differently, but for programs like that, try to make it as clear as possible.
OK. I knew that different companies had different standards they like
their code to follow.... wasn't sure if there was a globally
"gentlemans agreement" kind of deal outside of the ANSI/ISO that
everyone adhered to.
No. C++ can be used in toasters, you know.
Bummer. I knew it was diverse... but toasters....? :)
Or have a Google on std::vector. Do not stop on details like the weird std:: notation. Try to understand the whole.
I understand the std:: notation. At this level, I perfer to just call
it into the global namespace using "using namespace std;" and not do
all the extra typing. We are not going to use our own namespaces in
this class so I don't bother to much with it. Unfortunantly, beacuse
of that, I have less knowledge on what the whole namespace thing is
all about except for those responses a month ago when I had asked
about them. Thanks for the link, will check it out.
do { cout << "Do you want to continue(Y/N)?"; cin >> continue;
} while ( std::toupper(continue) != 'Y' );
If you are not familiar with this version of while, you can stay with the preceeding one, it is quite good. Or try this
while ( true ) // infinit loop { cout << "Do you want to continue(Y/N)?"; cin >> continue;
if ( std::toupper(continue) == 'Y' ) break; // exits the loop }
Ah, so you can use break to end any loop, not just a switch? I didn't
know that. That will help a great deal.
Hehe.. depends on the people.
That ok. I read the FAQ section on that. I always take things with a
grain of salt and try not to get up in arms at negative replies. Life
is to short to induce a heart attack... especially when your only 25.
:)
On Thu, 2 Oct 2003 18:59:40 +0100, "Buster" <no***@nowhere.com> wrote: Use a string, and use getline. You can look at the first position of a string using the [] indexing operator, but remember the positions are numbered from zero.
Ah, thats right. Thanks for the correction.
No, because `continue' is a keyword.
Ah, I knew that! Just slipped my mind when making the example. That
just shows I need to pay more attention to the little details and not
take things for granted in coding. :)
What would be simpler, though, is:
while (true) { std::cout << "Do you want to continue (Y/N)?\n";
std::string response; std::getline (std::cin, response);
if (response [0] != 'Y') break; }
Yes, I like this method much better. It was in Johnathans last post
that I learned you can "break" from any type of loop and not just
switch.
Thanks!!
"da Vinci" <bl***@blank.com> wrote Basically, take the function I am writing, take the first line of it, and post that at the top of the code as well?
Mostly, yes. In a 'real' program you might put the declarations
in a header file (and/or in a namespace or possible a class...)
but if you want to send your teacher a single compilable file
and you need to refer to a function before it is defined then
copy-paste is a nice easy way to do the forward declaration.
[...]
Ah, so you can use break to end any loop, not just a switch? I didn't know that. That will help a great deal.
I usually have to look it up. Let's see (from Borland online help):
"Use the break statement within loops to pass control to the first
statement following the innermost switch, for, while, or do block."
That last word always got me. It doesn't have to be a block, it can
be a statement, as in
for (int i = 0; i < 10; ++ i) if (std::rand () < 10) break;
That ok. I read the FAQ section on that. I always take things with a grain of salt and try not to get up in arms at negative replies. Life is to short to induce a heart attack... especially when your only 25. :)
Amen.
Regards,
Buster.
> > > > > cout << "\n\n\nSelection: "; > > Use std::endl instead of \n, which is not guaranteed to work > everywhere.
Eh?
-Mike
Mmm.. I though \n was not portable, I should have informed myself. Let me rephrase.
I prefer using std::endl since it is clearer than a bunch of \n. It is also supposed to flush the buffer, but flushing the buffer does not necessrily mean that the data is written.
Again, Eh?
I prefer using std::endl since it is clearer than a bunch of \n.
What's more, since std::cout is buffered, std::end flushes it. That
does not mean the output will automatically get on the stdout though,
since operating systems usually provide some buffering themselves
(this applies to all streams). To make sure the data gets written,
you should use implementation-specific functions which deal with
the operating system's buffer.
But usually, flushing the buffer is enough. Note that std::cout
flushes the buffer when it is destroyed (ie at the end of the
program), but you may have no time to see the output (in case
of outputting to stdout when there is a screen on your system)
so make sure you flush the buffer yourself when you are
finished writing.
Finally, '\n' may flush the buffer or not, this is not defined
(just as it may flush it with any character).
Interesting note that I found in my researches, \n is
translated into its equivalent depending on the platform.
For example, when writing to a text file, Windows needs a
\r\n and Mac gets a \r.
Jonathan
Jonathan Mcdougall wrote:
[SNIP] I prefer using std::endl since it is clearer than a bunch of \n.
What's more, since std::cout is buffered, std::end flushes it. That
[SNIP]
Sometimes it is better to not use std::endl but make a flush at the end.
For example if you are printing in a loop, there can be serious difference
in time.
--
WW aka Attila
"Jonathan Mcdougall" <jo***************@DELyahoo.ca> wrote in message
news:k5*******************@weber.videotron.net... I prefer using std::endl since it is clearer than a bunch of \n. It is also supposed to flush the buffer, but flushing the buffer does not necessrily mean that the data is written. Again, Eh?
I prefer using std::endl since it is clearer than a bunch of \n.
I disagree. Any C++ programmer will know what '\n' means.
As readily as what e.g. 'int' means. I suppose it can
vary among people, but I find '\n' simpler reading.
What's more, since std::cout is buffered, std::end flushes it.
Yes, I know. That's 'std::endl' :-)
That does not mean the output will automatically get on the stdout though,
Where did you hear that? What do you think 'flush' means,
in the context of an output stream?
since operating systems usually provide some buffering themselves (this applies to all streams).
Now you're outside the language. Nothing to do with
flushing a stream. And your generalization 'all streams'
is incorrect.
To make sure the data gets written, you should use implementation-specific functions which deal with the operating system's buffer.
I vehemently disagree. If this were the case, C++ would
fail in its role as a platform independent language.
But usually, flushing the buffer is enough.
"Usually", flushing a buffer is not necessary at all.
Note that std::cout flushes the buffer when it is destroyed
During 'cout's destruction, it (the stream) is flushed.
(ie at the end of the program), but you may have no time to see the output
Huh?
So you're saying that if I run:
#include <iostream>
int main()
{
std::cout << "Hello world\n";
return 0;
}
... that the output might disappear immediatly after
appearing on the output device to which 'cout' is
attached? I don't think so. An IDE might interfere
with a 'screen' output, but that's outside the language.
(in case of outputting to stdout when there is a screen on your system)
Absolutely not true.
so make sure you flush the buffer yourself when you are finished writing.
Unnecessary, unless you require that the output appear
*immediately* after inserting data into the stream.
And it's not even necessary if a 'cout' insertion
is followed by a 'cin' extraction, since by defintion,
a 'cin' extraction will first cause 'cout' to be flushed
if necessary (look up 'tie()'). Finally, '\n' may flush the buffer or not,
'\n' is not an operation. It's a value, that's all.
It cannot 'do' anything. A function might behave
in a particular way upon encountering it, this
behavior perhaps causing a flush.
this is not defined (just as it may flush it with any character).
Interesting note that I found in my researches, \n is translated into its equivalent depending on the platform.
That is common knowledge. It's a feature of a 'text mode'
stream, well documented.
For example, when writing to a text file, Windows needs a \r\n and Mac gets a \r.
I know this.
No offense, but I think you're suffering from a few
misconceptions.
-Mike
> > > > I prefer using std::endl since it is clearer than a bunch of \n. > It is also supposed to flush the buffer, but flushing the buffer > does not necessrily mean that the data is written.
Again, Eh? I prefer using std::endl since it is clearer than a bunch of \n.
I disagree. Any C++ programmer will know what '\n' means. As readily as what e.g. 'int' means. I suppose it can vary among people, but I find '\n' simpler reading.
This is a personal opinion. I like the look of
std::cout << "hey" << std::endl;
better than
std::cout << "hey\n"; That does not mean the output will automatically get on the stdout though,
Where did you hear that? What do you think 'flush' means, in the context of an output stream?
Ok let me rephrase that :)
Flushing will send the stream's content to stdout, but the operating
system is free to do whatever it wants with it. since operating systems usually provide some buffering themselves (this applies to all streams).
Now you're outside the language.
I know.
Nothing to do with flushing a stream. And your generalization 'all streams' is incorrect.
Explain. To make sure the data gets written, you should use implementation-specific functions which deal with the operating system's buffer.
I vehemently disagree.
woaa :)
If this were the case, C++ would fail in its role as a platform independent language.
I think we agree that after a buffer has been flushed, the
operating system is free to do whatever it wishes to,
like waiting for another operation to terminate before
completing writing the data.
Using implementation-specific functions will give you
more control on the way the data reaches
destination. That's all I meant. But usually, flushing the buffer is enough.
"Usually", flushing a buffer is not necessary at all.
What do you mean? (ie at the end of the program), but you may have no time to see the output
Huh?
So you're saying that if I run:
No.
#include <iostream> int main() { std::cout << "Hello world\n"; return 0; }
.. that the output might disappear immediatly after appearing on the output device to which 'cout' is attached? I don't think so. An IDE might interfere with a 'screen' output, but that's outside the language.
That is what I talked about, sorry, I was probably not
explicit enough. (in case of outputting to stdout when there is a screen on your system)
Absolutely not true.
What is not true? so make sure you flush the buffer yourself when you are finished writing.
Unnecessary, unless you require that the output appear *immediately* after inserting data into the stream.
That is what I meant, yes.
And it's not even necessary if a 'cout' insertion is followed by a 'cin' extraction, since by defintion, a 'cin' extraction will first cause 'cout' to be flushed if necessary (look up 'tie()').
Who's talking about cin? Finally, '\n' may flush the buffer or not,
'\n' is not an operation. It's a value, that's all. It cannot 'do' anything. A function might behave in a particular way upon encountering it, this behavior perhaps causing a flush.
To quote myself :
(just as it may flush it with any character). this is not defined (just as it may flush it with any character).
Interesting note that I found in my researches, \n is translated into its equivalent depending on the platform.
That is common knowledge. It's a feature of a 'text mode' stream, well documented.
So what? For example, when writing to a text file, Windows needs a \r\n and Mac gets a \r.
I know this.
That post was not intended to teach you things you know, it
was primarly for the op. But thanks for the corrections.
No offense, but I think you're suffering from a few misconceptions.
Perhaps.
Jonathan
"Jonathan Mcdougall" <jo***************@DELyahoo.ca> wrote in message
news:%L*******************@weber.videotron.net... > > I prefer using std::endl since it is clearer than a bunch of \n. > > It is also supposed to flush the buffer, but flushing the buffer > > does not necessrily mean that the data is written. > > Again, Eh?
I prefer using std::endl since it is clearer than a bunch of \n. I disagree. Any C++ programmer will know what '\n' means. As readily as what e.g. 'int' means. I suppose it can vary among people, but I find '\n' simpler reading.
This is a personal opinion.
Agreed.
I like the look of
std::cout << "hey" << std::endl;
better than
std::cout << "hey\n";
But note that the code one writes is quite often
read by others. This is imo good reasons to
follow 'convention'. Consistency Is Good(tm).
Also note that since 'endl' does cause a flush,
you're possibly slowing down the program, often
unnecessarily. This might not be noticable in some
cases, but could significantly impact performance
in others. E.g. writing 'endl' to an ofstream
attached to a file on a floppy disk, or other
inherently 'slow' device, such as a printer. That does not mean the output will automatically get on the stdout though, Where did you hear that? What do you think 'flush' means, in the context of an output stream?
Ok let me rephrase that :)
Flushing will send the stream's content to stdout,
Flushing will send any data not yet written to the
device to which the stream is attached.
but the operating system is free to do whatever it wants with it.
You're outside the language again. One cannot
comment further about 'behavior' at that point
from a language perspective. since operating systems usually provide some buffering themselves (this applies to all streams). Now you're outside the language.
I know.
Nothing to do with flushing a stream. And your generalization 'all streams' is incorrect.
Explain.
We're in a language perspective in this group. OS buffers
and their behavior are outside that domain.
"All streams" means all stream types, input, output,
or 'udpate' (input&output). Flushing is only defined
for output and 'update' streams.
Perhaps you were only being sloppy with terminology
and meant 'all output streams'. Which then would
omit 'update' streams. :-) To make sure the data gets written, you should use implementation-specific functions which deal with the operating system's buffer. I vehemently disagree.
woaa :)
If this were the case, C++ would fail in its role as a platform independent language.
I think we agree that after a buffer
make that 'stream', and by implication, that stream's
'stream buffer'. 'stream buffer' is a language construct,
not part of an OS.
has been flushed, the operating system is free to do whatever it wishes to,
An OS has nothing to do with the description of the
flush operation of a C++ stream.
like waiting for another operation to terminate before completing writing the data.
The device to which a stream is attached might be a 'real'
hardware device, or it might be one 'simulated' by an
OS (e.g. 'virtual device' such as a 'RAM-disk'). The
behavior of such devices and control of such by an OS
is outside of a discussion about C++ streams. Using implementation-specific functions will give you more control on the way the data reaches destination. That's all I meant.
Well, yes, platform-specific features can give 'finer-grained'
control over a system, but that's nothing to do with C++
streams, which are an *abstraction* of external data. But usually, flushing the buffer is enough. "Usually", flushing a buffer is not necessary at all.
What do you mean?
I mean that in many situations, the 'automatic' flushing
of an output stream will already occur, as in my 'cout'
followed by 'cin' example. Also it's often good enough
to simply let flushing happen automatically when an output
stream gets destroyed. Of course there can be exceptions
to this, depending upon the problem domain. "Usually"
can mean many things to various people. It usually :-)
means "common to a person's experiences and observations." (ie at the end of the program), but you may have no time to see the output
Huh?
So you're saying that if I run:
No.
#include <iostream> int main() { std::cout << "Hello world\n"; return 0; }
.. that the output might disappear immediatly after appearing on the output device to which 'cout' is attached? I don't think so. An IDE might interfere with a 'screen' output, but that's outside the language.
That is what I talked about,
Which part of the paragraph I wrote after that code
are you talking about? Is your answer to the question
yes or no? Were you talking about the 'IDE interference'?
If so, C++ stream flushing has nothing to do with that.
sorry, I was probably not explicit enough.
Effective communication can often be difficult. :-) (in case of outputting to stdout when there is a screen on your system)
Absolutely not true.
What is not true?
Probably should have said "not necessarily true".
... that if std::cout is attached to a video display,
the data displayed after a flush might 'disappear'.
Nothing about the C++ streams will cause (or prevent) this
behavior. The data will be sent to the device (or if you
prefer, to the OS's interface for it). What happens after
that is outside the language. so make sure you flush the buffer yourself when you are finished writing.
Unnecessary, unless you require that the output appear *immediately* after inserting data into the stream.
That is what I meant, yes.
But you were talking about this happening at program
termination. I meant 'midstream' during execution
where data is being output. And it's not even necessary if a 'cout' insertion is followed by a 'cin' extraction, since by defintion, a 'cin' extraction will first cause 'cout' to be flushed if necessary (look up 'tie()'). Who's talking about cin?
I gave it as a common example. It's very common to
have code such as:
std::cout << "Your name: ";
std::cin >> name;
There's no need to flush cout to ensure the prompt
appears before the input request occurs. This is
done automatically by default, via 'tie()'.
Contrast C's stdin and stdout, where a prompt
using 'printf()' needs a subsequent flush
before an input request e.g. with 'scanf()',
to ensure the prompt appears first. Finally, '\n' may flush the buffer or not,
'\n' is not an operation. It's a value, that's all. It cannot 'do' anything. A function might behave in a particular way upon encountering it, this behavior perhaps causing a flush.
To quote myself : (just as it may flush it with any character).
I suppose I could have misunderstood your meaning.
No, there is nothing preventing the stream buffer
being flushed at whatever point the library implementor
(or a coder using a custom stream buffer) determines is
appropriate (this could be upon insertion of a character
with a certain value such as '\n' or some other value,
but there's no requirement for it).
One condition under which a flush with *always* happen
is when a character (with *any* value) is inserted,
but the stream buffer is already full. The stream
buffer must first be flushed in order to make room
for the new character. this is not defined (just as it may flush it with any character).
Interesting note that I found in my researches, \n is translated into its equivalent depending on the platform.
That is common knowledge. It's a feature of a 'text mode' stream, well documented.
So what?
It just seemed to me that you felt you were pointing
out something not obvious to most C++ programmers. For example, when writing to a text file, Windows needs a \r\n and Mac gets a \r. I know this.
That post was not intended to teach you things you know, it was primarly for the op.
And anyone else reading. I try to intercept incorrect
or unclear information being imparted here. It also
gives others a chance to point out when I err myself.
But thanks for the corrections.
You're welcome. Please be assured that my motives
are educational, not attempts to appear 'smarter'
than you or anyone else. You should have seen the
confusion I sometimes suffered when learning C, so
many years ago. :-) No offense, but I think you're suffering from a few misconceptions.
Perhaps.
Hope you've found my comments helpful.
-Mike
> >Be careful with them though. I suggest you take a look to std::vector before arrays, since arrays are error-prone, but I suppose your teacher knows what she's doing. Actually, I am 2 months ahead in all of my assignments. So I am basically self teaching myself function use and everything else until the class catches up.
Unfortunately, that is quite frequent with school. The best thing you
can do now is to help people. That will make you learn a lot. There
is nothing better than a stupid question to make you doubt about your
knowledge, forcing you to search for the answer.
Maybe silly, but easy questions are often harder to answer than
difficult ones.
I was personally going to learn arrays next, but will look at vectors first if that is the better approach. Thing is, I know the basics of arrays already. I know nothing of vectors except what I learned in Physics.... but I doubt that is what were talking about here. :)
He. _Simply put_, a vector is an array which grows dynamically.
But since it does all the memory management itself, it is much
easier and safer to use.
OK, I think I see what you mean. Basically, instead of declaring a function with
int This_Function(int, int, int);
use
int This_Function (int var1, int var2, int var3)
then write the code for the function starting with the same line. Basically, take the function I am writing, take the first line of it, and post that at the top of the code as well?
If you want to put declaration in the same file, yes. If not, do
the same thing, but paste it in another file :) No. Depending on the company standards, you will do things differently, but for programs like that, try to make it as clear as possible.
OK. I knew that different companies had different standards they like their code to follow.... wasn't sure if there was a globally "gentlemans agreement" kind of deal outside of the ANSI/ISO that everyone adhered to.
No, there are a couple of guidelines and you will learn them as you
post here. Or have a Google on std::vector. Do not stop on details like the weird std:: notation. Try to understand the whole.
I understand the std:: notation. At this level, I perfer to just call it into the global namespace using "using namespace std;" and not do all the extra typing.
Namespaces are not only "extra typing". The basically avoid name
clashes. For example, having a class named 'vector' in your program
would clash with the standard vector class. Putting them into
namspace avoids that.
The thing is, you have absolutly no idea what classes are in the
namespace std in the headers you are including, so you could end
with weird compile errors.
We are not going to use our own namespaces in this class so I don't bother to much with it.
The good thing is that most librairies are in a namespace themselves,
so your code is quite protected from that, unless you dump all the
names with the using declaration.
Unfortunantly, beacuse of that, I have less knowledge on what the whole namespace thing is all about except for those responses a month ago when I had asked about them. Thanks for the link, will check it out.
Buy a book! If you never did programmation before, I recommend
something like "Thinking in C++" by Eckel (have a google, his book
is online). If not, get Accelerated C++ bu Koenig and Moo and
eventually the c++ bible "The C++ programming language" by
Stroustrup. do { cout << "Do you want to continue(Y/N)?"; cin >> continue;
} while ( std::toupper(continue) != 'Y' );
If you are not familiar with this version of while, you can stay with the preceeding one, it is quite good. Or try this
while ( true ) // infinit loop { cout << "Do you want to continue(Y/N)?"; cin >> continue;
if ( std::toupper(continue) == 'Y' ) break; // exits the loop }
Ah, so you can use break to end any loop, not just a switch? I didn't know that. That will help a great deal.
'break' breaks out of switch, do, while and for.
The most important thing is : stick up with this newsgroup, post, read,
comment, ask. That way you will learn much more than what you can do
in class or at home. Believe me. People here bark a lot, but they
don't bite :)
Jonathan This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Chuck |
last post by:
Hello,
I have an Access XP database that has several fields. One of the
fields is a text field and has an account number that is preceeded by
a text character, like: F102354. Every account...
|
by: Chuck |
last post by:
I have a question tht I'm sure someone out there can answer.
A friend of mine has developed an Access application that is a very
business specific (niche type of application). The application...
|
by: Chuck |
last post by:
I have a query that uses the query with the critera set to . We I run the query the msgbox pops up asking for
the name information to be entered, but on the top (blue background)
of the message box...
|
by: Chuck |
last post by:
I am trying to retrive one field from the "company info" table that
contains several fields but I want the "company name" field. There is
only one record in this table. When I entered the code...
|
by: Chuck |
last post by:
I appreciate any help!!!
I have an application that has 4 different forms that display the same
information except for the fact that they are fed from 4 different
parameter queries. The 4...
|
by: WØCBF |
last post by:
I have an Access application that was written in ver 2002. I have
distributed the application to our other offices using the Developers
Toolkit and installed a runtime version of Access. At that...
|
by: WØCBF |
last post by:
I know this code has worked before but now appears to get a compile
error. The code it seems to choke on line 12.
I receive the following message and it highlights the "rst!" statement.
Error...
|
by: DJRhino |
last post by:
Was curious if anyone else was having this same issue or not....
I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
|
by: isladogs |
last post by:
The next Access Europe meeting will be on Wednesday 4 Oct 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM)
The start time is equivalent to 19:00 (7PM) in Central...
|
by: Aliciasmith |
last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
|
by: tracyyun |
last post by:
Hello everyone,
I have a question and would like some advice on network connectivity. I have one computer connected to my router via WiFi, but I have two other computers that I want to be able to...
|
by: NeoPa |
last post by:
Hello everyone.
I find myself stuck trying to find the VBA way to get Access to create a PDF of the currently-selected (and open) object (Form or Report).
I know it can be done by selecting :...
|
by: NeoPa |
last post by:
Introduction
For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
|
by: Teri B |
last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course.
0ne-to-many. One course many roles.
Then I created a report based on the Course form and...
|
by: isladogs |
last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM).
In this month's session, Mike...
|
by: GKJR |
last post by:
Does anyone have a recommendation to build a standalone application to replace an Access database? I have my bookkeeping software I developed in Access that I would like to make available to other...
| |