--Originally published at my programming blog
The WSQ of last week was to make a program that could read a file and return how many lines and how many characters does it have.
This links were very useful for the use of structs, how to count the lines in a file and to count how many characters .
So what I did was:
- I included the fstream library ,so that I can read the file, and the string library so that I can use the getline function.
- Then I created my struct, I named it Results and I declared my two integers that my function will return at the end, which are sum (the number of characters) and number_lines (number of lines).
- Then I created my function and I wrote Results (to make reference to my struct) and then I named it printResults and in the parameters I wrote Results(the struct)”&” w, which means that any variable that has “w.” will be directed to the struct.
- I declared my variables that the function will return (sum and number_lines).
- Then I declared the ifstream “file” and the name of my file in parenthesis which is “TextFile.txt”.
- Then I did an if loop and the condition was that if the file was open then i would do the following:
- A while loop and in the condition I included a getline (function that counts the number of lines) and inside the getline the parameter are the ifstream file and the string line.
- Then inside that loop I did number_lines++, which means that it will give me how many lines by repeating the loop while there are more lines.
- Then I declared an integer called NumOfChars and I assigned it to the length of the string line (line.length()) (length is another function of the string library).
- Then I Continue reading "Multipart Data and Files"