More Loops
These first few are from chapter 3, but we skipped them.
size_t find(string pattern [, size_t pos=0]
- This is a string class member function
- size_t is a user defined type
- Defined by the people who implemented the string function.
- Probably an unsigned integer.
- But we can treat it as an int, with the compiler only occasionally complaining.
- In which case, a cast will take care of things.
- In strings, positions start at 0.
- It searches the string for a pattern starting at the given position
- The position is optional, and assumed to be 0 if not given.
- If the pattern is not found
string::npos
is returned.
Write a program to find the number of times a word occurs in a string.
(i.e. how many times does "Dan" appear in "Danger, Danger, Danger!"
string substr(size_t pos, size_t lend)
- This is another string member function.
- It will extract a substring from a string.
- We could write this if we wanted to but...
- pos is where to start extracting the substring.
- len is the length of the substring to extract.
- len can be longer than the length of the string.
- In this case, it returns from the start position to the end of the string.
- Write a program to read in a list of words, separated by commas
print the individual word without the commas.
And a non-string function or two.
- int rand()
- Generate a random number between [0, RAND_MAX]
- You need #include < cstdlib>
- This is not a true random number, it is a pseudo-random number
- The same sequence is always produced.
- ri = f(ri-1)
- Try this.
- We can change the starting point of the sequence with srand(int seed)
- YOU ONLY CALL srand ONCE PER PROGRAM.
- srand(5) will give a different default sequence.
- This is useful for debugging programs which involve randomness, you eliminate the real randomness.
- srand(time(NULL)) is good for random programs
Write a program that prints 5 random numbers between 1 and 6 (rolls a six sided die five times)
Write a program that emulates a magic 8 ball. The user types a question, the magic 8 ball repeats the question and provides an answer.
- Do you understand the problem?
- In the traditional 8 ball, there are 5 negative, 5 neutral and 10 positive answers.
- Algorithm?
- Test Cases? - probably not.
- eightBall.cpp