logo CodeStepByStep logo

coinFlip

Language/Type: C++ basics streams file input
Related Links:
Author: Marty Stepp (on 2016/06/16)

Write a function named coinFlip that accepts as its parameter a string holding a file name, opens that file and reads its contents as a sequence of whitespace-separated tokens. Assume that the input file data represents results of sets of coin flips. A coin flip is either the letter H or T, or the word Heads or Tails, in either upper or lower case, separated by at least one space. You should read the sequence of coin flips and output to the console the number of heads and the percentage of heads in that line, rounded to the nearest whole number. If this percentage is 50% or greater, you should print a "You win!" message; otherwise, print "You lose!". For example, consider the following input file:

H  T H  H    T
Tails taIlS   tAILs TailS heads   HEAds
   hEadS

For the input above, your function should produce the following output:

6 heads (50%)
You win!

The format of your output must exactly match that shown above. You may assume that the file contains at least 1 token of input, and that no tokens other than heads/tails or H/T will be in the lines. If the input file does not exist or is not readable, your function should print no output.

Constraints: Your solution should read the file only once, not make multiple passes over the file data.

Type your C++ solution code here:


This is a function problem. Write a C++ function as described. Do not write a complete program; just the function(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.

© Marty Stepp, all rights reserved.