I was to make code that will deter. which digit appears as the first digit most often in a given data set. Each execution will deter. the result for one file. I need to read in the data in a loop that will continue until the end of the file. For each number read in, i need to call a method(i will write) that returns the first digit of the # passed to it. For example, if number passed was 14829, the function should return a 1. If was 43, function should return 4. Once I have the first digit, the program should update the tallies of first digits. I need to declare a variable for each digit 1-9, to hold # of values in the file that start with that digit. use switch structure to update approp. accumulator. Once #s are read, print out each digit and the tally of its appearance as a first digit. Example execution:
http://i32.tinypic.com/10n6zjr.jpg
- I also have a file .txt that has a list of numbers and i named it librarybooks-1.txt
- Here is some code I have started and need help please.
C++ code help with loops?
(1) Use an array instead of separate vars for each total
(2) You don't need a 1st digit function, it is the first char in each string
(3) You don't need the switch statement if you use the array
#include %26lt;iostream%26gt;
#include %26lt;fstream%26gt;
#include %26lt;cctype%26gt;
using namespace std;
int main()
{
ifstream inFile("librarybooks-1.txt");
if (! inFile)
{
cout %26lt;%26lt; "Could not open inputfile"%26lt;%26lt; endl;
exit(1);
}
int totals[10] = {0};
string str;
while (getline(inFile, str))
{
if (! isdigit(str[0]))
continue;
else
totals[str[0] - '0']++;
}
for (int i = 0; i %26lt; 10; ++i)
{
cout %26lt;%26lt; "Number of " %26lt;%26lt; i %26lt;%26lt; "'s : " %26lt;%26lt; totals[i] %26lt;%26lt; endl;
}
}
Reply:It looks like num1 would be the line while num11 is the entire document.
In that case test if num1[0] is a number.
if(atoi(num1[0])%26gt;=0 %26amp;%26amp; atoi(num1[0])%26lt;=9)
cout %26lt;%26lt; "Number is: " %26lt;%26lt; num1[0] %26lt;%26lt; endl;
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment