OK, so I am a first-year university student, currently in Computer Science I, an Introduction to Linux and C++. This is also my first time using these forums, so please, go easy on me! :)
I have a homework assignment here, and I know I am not supposed to ask for homework solutions on here, but my teacher is absolutely terrible at explaining functions and character input. Im not only asking for the solution to my problem, I am asking for somebody to try and explain how they got to the solution, so that I can understand how to do it, and how to use functions. OK, so here goes, this is the assignment my teacher has posted:
Design, code and test a C++ program (stored in the file countcharsv2.cpp) that will count all of the characters in a file lab7.dat. In addition, this program will
* output the number of whitespace (as defined by the function isspace) characters in lab7.dat.
* output the number of lines in lab7.dat.
* echo each input character to standard output - followed by its ASCII code as shown below.
* output CHARS_PER_LINE character-ASCII code pairs per line.
Do not use nested loops in this program. For the given lab7.dat file, a typical program run should look very much like ...
$ ./a.out
H- 72 i-105 - 32 B- 66 o-111 b- 98 !- 33 \n-10 \n-10 T- 84
h-104 i-105 s-115 - 32 - 32 - 32 - 32 l-108 a- 97 s-115
t-116 - 32 l-108 i-105 n-110 e-101 - 32 i-105 s-115 - 32
a- 97 - 32 l-108 i-105 t-116 t-116 l-108 e-101 - 32 l-108
o-111 n-110 g-103 e-101 r-114 .- 46 - 32 - 32 \n-10 - 32
- 32 - 32 \n-10 - 9 \n-10
There are 55 characters in the file lab7.dat
There are 21 whitespace characters in the file lab7.dat
There are 5 lines in the file lab7.dat
$
To produce this output, you will need to
1. output the ASCII code for each character. Simply assign the char value to an int variable and output the int variable.
2. use the function setw(int n) to set the field width used to output the ASCII code to 3.
Also note ...
* Note that there is a tab character on the last line of the given lab7.dat file.
* You could compare your results with those from the wc utility ... use the Linux command
$ wc lab7.dat
OK, so now that you all can see my assignment, I think you'll agree that it would be VERY difficult to create this program without a proper knowledge of functions.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
const int CHARS_PER_LINE = 10;
const string FILENAME = "lab7.dat";
int main()
{
ifstream fin;
fin.open(FILENAME.c_str());
if (fin.fail())
{
cout << "ERROR: Unable to open \"" << FILENAME << "\"\n";
exit(1);
}
return 0;
}
|
That is what I have so far, just a basic skeleton of the program, and I am having trouble deciding what to do next, and where to place everything. The last thing I want is a long program, only to find out there is an error in the middle, and i have to rewrite it.
Any help would be appreciated!!! :)