473,765 Members | 2,059 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A small question

Hello everyone,

I'm just getting started playing around with C++, so please don't laugh
too loudly at my crude source code, okay? (o^^o)

I'm combining together several introductory exercises into one small
program. My compiler and IDE is Visual C++ Express Edition, and the
book I'm using is Teach Yourself C++ in 24 hours by Jesse Liberty and
David Horvath. While playing around with the code a little bit I found
something I couldn't understand.

The program only uses "int" variables (except for one small string). I
have a function called "LoopExp" that takes input from the user and
stores it in FirstNumber. LoopExp then calls another function,
"CompareNumbers " to do a quick division exercise. Naturally, I need
two numbers, so CompareNumbers gets a variable called SecondNumber from
the user.

If the user inputs a number with a decimal point for FirstNumber (i.e.,
4.5), then the CompareNumbers function pulls garbage off the stack and
will not run correctly. I tried using a forced typecast on
FirstNumber, int(FirstNumber ), but naturally the compiler returned an
error.

Is there an easy way to prevent CompareNumber from pulling garbage off
the stack or do I just have to wait until I study exception handling?

The source code is below. Many thanks to anyone who takes the time to
offer a reply!

Brian K. Miller

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

#include <iostream>

using namespace std;

void LoopExp(); // Declare the LoopExp()
function
void CompareNumbers( int FN); // Declare the CompareNumbers( )
function
int main()
{
char Name[64];

cout << "\nIs this thing on?" << endl;
cout << "Oh, sorry! I guess it is." << endl;
cout << "As long as I have your attention, what's your name?\t";
cin >> Name;
cout << "Hello, " << Name << ". Pleased to meet you!" << endl <<
endl;

// From this point we call some functions containing other
examples

LoopExp(); // Contains an example of a simple do-while loop

return 0;
}

void LoopExp()
{
/* This function asks for a number from the user, checks to make
sure their input is within bounds (but does NOT check for
character
input!) then outputs "I love games!" to the screen for the same
number of times as the user's input.
*/

int FirstNumber = 0;

cout << "So, let's play a game! Give me a number from 1 to 10: ";
cin >> FirstNumber;

/*
NOTE: If the user inputs a number with a decimal point (i.e.,
4.5)
for FirstNumber then the CompareNumbers( ) function will not
work
properly and the program will display garbage!
*/

CompareNumbers( FirstNumber);

if (FirstNumber < 1 || FirstNumber > 10) // check for an input
error
{
cout << "You're no fun!" << endl;
}
else
{
do
{
cout << "I love games!" << endl; // output the message
FirstNumber--; // decrement
the number
} while (FirstNumber != 0);
} // end of if-else

cout << endl; // move cursor down one line

} // end of LoopExp()
void CompareNumbers( int FirstNumber)
{
/* This function asks for a second number larger than the first,
but less than 100. It then uses the modulus operator to see
if they are evenly divisible. If they are, it checks to see
if the user entered 10 twice (the only possible duplication).
If the numbers are evenly divisble it outputs the correct
answer.
If they are not evenly divisble, it apologizes and outputs
the integer component of the answer.

NOTE: If the user inputs a number with a decimal point for
SecondNumber, then the program will strip off the remainder
and just use the integer portion.
*/

int SecondNumber = 0;
int Temp = 0;
int FN = 0;

FN = FirstNumber;

cout << "Now give me a number between 10 and 100: ";
cin >> SecondNumber;

if (SecondNumber < 10 || SecondNumber > 100) // check for an
input error
{
cout << "Hey! " << SecondNumber << " is not what I asked for!"
<< endl;
}
else
{
Temp = SecondNumber / FN;

if ((SecondNumber % FN) == 0) // check if they are evenly
divisble
{
if (SecondNumber == FN)
{
cout << "You really like the number 10, don't you?" <<
endl;
}
else
{
cout << "\nOh, cool! They are evenly divisible!" <<
endl;
cout << "The second number divided by the first is: " <<
Temp << endl << endl;
} // end of "Oh, cool!"
} // end of "check for evenly divisible"
else
{
cout << "\nI tried to divide " << SecondNumber << " by " <<
FN;
cout << ", but I can't do fractions." << endl;
cout << "Still, " << Temp << " is pretty close, right?" <<
endl << endl;
} // end of "I can't do fractions"
} // end of else section following initial error check for
SecondNumber
} // end of CompareNumber()

Feb 28 '06 #1
2 2057
BKMiller wrote:
If the user inputs a number with a decimal point for FirstNumber (i.e.,
4.5), then the CompareNumbers function pulls garbage off the stack and
will not run correctly.
Well, more precisely, 'FirstNumber' will become "4" and the next
character to be read will be "." which is not a valid start for
an 'int'. Thus, the next attempt to read an 'int' from the stream
will fail, set corresponding state flags in the stream, and leave
the corresponding variable uninitialized.

You should always check the result from input, especially if it is
manual input. This could look like this:

if (std::cin >> var)
/* processing of successful read goes here */
else
/* processing of wrong input goes here */

Depending on what you are doing, recovery from an input error may
take different forms. In your situation you probably want to try
to recover from the error situation, e.g. by ignoring everything
on the current line:

// execute the loop until we could either successfully read
// a value or end of file is reached:
while (!(std::cin >> var) && !std::cin.eof() )
{
std::cin.clear( ); // clear the error flags
// ignore an arbitrary amount of character until end of line
std::cin.ignore (std::numeric_l imits<std::stre amsize>::max(), '\n');
}
if (std::cin.eof() )
throw std::runtime_er ror("EOF while reading a value");

In many situations no recovery is attempted and the processing of
the file is immediately terminated with an appropriate error.
Is there an easy way to prevent CompareNumber from pulling garbage off
the stack
Actually, this is not at all happening.
char Name[64];
cin >> Name;


This is a receipt for buffer overflows! There are two options to
make sure that no buffer overflow occurs:

1. The preferred option is to use an 'std::string' instead of a
fixed size array:

#include <string>
// ...
std::string Name;
std::cin >> Name;

This is less error-prone and accommodates for the possible use
of rather long names.

2. You can setup the maximum number of characters to be read by
setting the width:

#include <iomanip>
// ...
char Name[64];
std::cin >> std::setw(sizeo f(Name)) >> Name;

This will limit the number to be read to be 'sizeof(Name) - 1'.
The extra character is need to store a terminating null character.
--
<mailto:di***** ******@yahoo.co m> <http://www.dietmar-kuehl.de/>
<http://www.eai-systems.com> - Efficient Artificial Intelligence
Feb 28 '06 #2
On 27 Feb 2006 22:56:32 -0800, "BKMiller" <su*****@hotmai l.com> wrote:
<...>

Is there an easy way to prevent CompareNumber from pulling garbage off
the stack or do I just have to wait until I study exception handling?
Yes, test if input conversion has failed
<...>void LoopExp()
{
/* This function asks for a number from the user, checks to make
sure their input is within bounds (but does NOT check for
character
input!) then outputs "I love games!" to the screen for the same
number of times as the user's input.
*/

int FirstNumber = 0;

cout << "So, let's play a game! Give me a number from 1 to 10: ";
cin >> FirstNumber;

/*
NOTE: If the user inputs a number with a decimal point (i.e.,
4.5)
for FirstNumber then the CompareNumbers( ) function will not
work
properly and the program will display garbage!
*/
if (cin.fail()) {/*Do whatever you think is fit */}

CompareNumbers( FirstNumber);
<...>void CompareNumbers( int FirstNumber)
{
/* This function asks for a second number larger than the first,
but less than 100. It then uses the modulus operator to see
if they are evenly divisible. If they are, it checks to see
if the user entered 10 twice (the only possible duplication).
If the numbers are evenly divisble it outputs the correct
answer.
If they are not evenly divisble, it apologizes and outputs
the integer component of the answer.

NOTE: If the user inputs a number with a decimal point for
SecondNumber, then the program will strip off the remainder
and just use the integer portion.
*/

int SecondNumber = 0;
int Temp = 0;
int FN = 0;

FN = FirstNumber;

cout << "Now give me a number between 10 and 100: ";
cin >> SecondNumber;
if (cin.fail()) {/*Do whatever you think is fit */}

if (SecondNumber < 10 || SecondNumber > 100) // check for an
input error
{
cout << "Hey! " << SecondNumber << " is not what I asked for!"
<< endl;
}
else
{
Temp = SecondNumber / FN;

if ((SecondNumber % FN) == 0) // check if they are evenly
divisble
{
if (SecondNumber == FN)
{
cout << "You really like the number 10, don't you?" <<
endl;
}
else
{
cout << "\nOh, cool! They are evenly divisible!" <<
endl;
cout << "The second number divided by the first is: " <<
Temp << endl << endl;
} // end of "Oh, cool!"
} // end of "check for evenly divisible"
else
{
cout << "\nI tried to divide " << SecondNumber << " by " <<
FN;
cout << ", but I can't do fractions." << endl;
cout << "Still, " << Temp << " is pretty close, right?" <<
endl << endl;
} // end of "I can't do fractions"
} // end of else section following initial error check for
SecondNumber
} // end of CompareNumber()

Regards,

Zara
Feb 28 '06 #3

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

Similar topics

7
3942
by: Randall Parker | last post by:
Using IE 6.x (whatever is the latest) on Windows 2000. For these two CSS definitions if I remove the 2 lines that have the "mso-" font family definitions (mso-fareast-font-family, and mso-bidi-font-family) then the "SmallerText" assigned as a class to a div tag produces larger text than the "SmallerText2". So x-small is treated as a bigger font size than plain old small. How the heck is one supposed to know all the MS stuff one needs...
7
1266
by: Sharon | last post by:
Hiya I have a small question, I saw this piece of code somewhere (it's for creating a customized context menu) and I was wondering: Why is it that the STYLE and SCRIPT-tags are broken up into parts? I hope someone can answer my question, thanks! Sharon html+='<TABLE STYLE="border:1pt solid #808080" BGCOLOR="#CCCCCC" WIDTH="140" HEIGHT="220" CELLPADDING="0" CELLSPACING="1">'; html+='<ST'+'YLE TYPE="text/css">\n'; html+='a:link...
3
1987
by: Tim | last post by:
Hi Group, Apologies if this is a bit OT (if so, please advise where it should be posted). I was wondering if anyone had any ideas as to what applications could work in a system where the server has a large storage and fast processing speed, but the client is connected via a small bandwidth? Assuming many clients could be connected simultaneously.
5
1984
by: Geoff Cox | last post by:
Hello Would be grateful if someone can make a few things clear for me! I have developed a small app using Java and would like to do the same using C++ but without the need for a runtime environment addition. This is a very samm app and it seems foolish to have to ask the user to install 20 MB of extra software. The app displays an image and a question asks the user to indicate
1
1241
by: Gena | last post by:
Hi , I'm a newbe to programming and have a small question: I made a small program with a class. in the class's header file I have : double *ptr_output; Void main() { double result;
4
2047
by: =?Utf-8?B?VzFsZDBuZTc0?= | last post by:
When one architects a new project one of the first steps in the decision is to decide on the layers. (In my opinion anyway) One architecture that I have used before is to go solid OO and create objects, which normally are very small and only deals with the stuff pertaining to that object, then break it down into Business Process, Process Controllers and Data Access Objects for each "Object", each of which is created in it's very own .Net...
1
2488
by: =?Utf-8?B?cmJiZW5zb24=?= | last post by:
To begin,, the network infactructure- Servers - Server00 - Windows Server 2003/Installed Server01 - Windows Server 2003/plan to install Server10 - Linux RedHat Workstation/Installed Client/Workstations - Client 00 - Windows XP Pro/Installed Client 01 - Windows XP Home/Installed
169
9180
by: JohnQ | last post by:
(The "C++ Grammer" thread in comp.lang.c++.moderated prompted this post). It would be more than a little bit nice if C++ was much "cleaner" (less complex) so that it wasn't a major world wide untaking to create a toolchain for it. Way back when, there used to be something called "Small C". I wonder if the creator(s) of that would want to embark on creating a nice little Small C++ compiler devoid of C++ language features that make...
4
3668
by: ATS16805 | last post by:
Hi. I wonder if it's possible to "force" a browser to "switch to SSR mode" for any given document. Specifically, I'm looking for a solution, not to a User Agent issue (i think), but a coding idea; a programming "what if..?". i'm not concerned w/ manipulating a browser (i.e. prefs., settings this URL, always view SSR, save), but rather something i would code into the document which would request the browser to display in this mode (i.e....
0
9399
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10163
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10007
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9957
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8832
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3924
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.