Counting Char from InFile
Feb 22, 2016 at 2:39am UTC
I must count Characters from a text file I read in. Store them in a Char Array, and then print how many characters were actually in the text file. Here is what I have so far. (I cant even get it to compile)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#include<iostream>
#include<fstream>
using namespace std;
int getFileLength(ifstream inFile);
int main(){
ifstream inFile;
int length = 0;
length = getFileLength( inFile );
cout << length;
return 0;
}
int getFileLength(ifstream inFile){
int length = 0;
char arr[600];
inFile.open("test.html" );
inFile >> arr;
if (inFile)
++length;
return length;
}
Feb 22, 2016 at 2:58am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include<iostream>
#include<fstream>
using namespace std;
int getFileLength(ifstream& inFile);
int main(){
ifstream inFile;
int length = 0;
length = getFileLength(inFile);
cout << length;
return 0;
}
int getFileLength(ifstream& inFile){
int length = 0;
char arr[600];
inFile.open("test.html" );
if (inFile.is_open())
{
while (inFile >> arr)
{
length++;
}
}
else
{
cout << "Failed to open file" << endl;
}
return length;
}
Feb 22, 2016 at 3:08am UTC
Dang, I was so close! Hmm, It is counting words , but I need characters...the battle continues, BUT THANK YOU.
Feb 22, 2016 at 3:11am UTC
If you want to count characters and not words, then there is no point of having a char array, a simple char would do the trick -
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
#include<iostream>
#include<fstream>
using namespace std;
int getFileLength(ifstream& inFile);
int main(){
ifstream inFile;
int length = 0;
length = getFileLength(inFile);
cout << length;
system("pause" );
return 0;
}
int getFileLength(ifstream& inFile){
int length = 0;
char arr; // a char, not char array
inFile.open("test.html" );
if (inFile.is_open())
{
while (inFile >> arr)
{
length++;
}
}
else
{
cout << "Failed to open file" << endl;
}
return length;
}
Feb 22, 2016 at 3:34am UTC
I see ... and appreciated. Now on to the next fcn!
Topic archived. No new replies allowed.