
|
|
[
Pre-packaged Functions ::
Strings in C++ ::
Style Considerations ::
Exercise #6 ]

|
When given a problem, you many time see that you need a specific function in order to accomplish your task.
Such a function may be the sin of an angle. For this reason we can use Pre-packaged Functions.
The only thing we need to do is to scan the documentation of a particular library and try to find the
function that meets our needs. After that we have to include the library that contains this function and then
we can call it directly.
|
Example using (sin) from (math.h).
/* sin example */
#include <stdio.h>
#include <math.h>
#define PI 3.14159265
main ()
{
double param, result;
param = 45;
result = sin (param*PI/180);
printf ("Sine of %lf degrees is %lf\n", param, result );
return 0;
}
Output:
Sine of 45.000000 degrees is 0.707107
|
( Use these libraries and add powerful functionality to your programs )
[ ::
::
::
::
::
]
|
Top

|
/* returns true if the given character is an integer (look at the table below)*/
bool isDigit(char c)
{
return (c>=48 && c<=57);
}
/* returns true if the given string is a real number */
bool isReal(string instring)
{
int size = instring.size();
int dotcount = 0;
char c;
for (int i=0; i<size; i++)
{
c = instring[i];
if (c=='.')
{ dotcount++; }
else if (!isDigit(c))
{ return false; }
}
/* check if this number has more than 1 dots '.' */
if (dotcount<=1)
{ return true; }
else
{ return false; }
}
|
Top

|
(See C++ Style Guidelines handout posted on Pr.Kelsey web page.)
- Use blank lines to separate set of related instructions.
- Liberally use clear and helpful comments.
- Make comments stand out - end of line (lined up) or blank line above comment.
- Type each statement on a separate line.
- Avoid running a statement over multiple lines.
- Avoid line splicing (line too long)
- Indent lines after a curly brace by the same amount until the end curly brace.
- Use whitespace in typing statements (cout<<"Hello all"; cout << “Hello all”;)
|
Top

|
New! - Download lab6.exe (win32) here and see how your program should behave to various inputs,
See Solution - C++ solution here (will be available on Saturday 2/16/02)
Write a program that randomly picks a number between 2 and 8 then asks the user to enter a word that contains that many characters.
Check to see if the word they entered does indeed have the correct number of characters and output whether they entered a good word or not.
Let them continue to do this as many times as they want each time using a different random number.
For example, if the random number was 5 and they user entered "cross" then you should output that they entered a good
word, but if they had entered "bucket" then you should output that they did not enter a word with the correct number of characters.
Notice: Be sure to put all your information (login, lab section, …) at the top of your program. Your lab programs DO NOT get turned in electronically. I will come around and check you off individually.
|