#include <iostream>
#include <string>
#include <fstream>
usingnamespace std;
int countCharacters(string file);
int main(){
countCharacters("Bradbury1.txt");
return 0;
} // end of main
int countCharacters(string file){
int numOfchars = file.length();
for (unsignedint i = 0; i < file.length(); i++){
if (file.at(i) == ' '){
numOfchars--;
}
cout << "Number of Characters: " << numOfchars << endl;
}
}
Would I put it in my main, or within my actual function.
Either one would work. It really depends on where you would need to use the file stream and how long you need to keep the defined file stream around.
If it is just used in the function I would setup and open the file stream in the function. And when the function looses scope the stream will close and the variable will be destroyed.
If you setup the "ifstream" in "main" then you will have to pass it to the function and pass by reference.
file is a string *representing* the NAME of the file.
it is not a file.
a file is of type fstream, or ifstream (input) or ofstream(output).
eg
ifstream reallyafile(file); //attempts to open 'file'
or
ifstream reallyafile;
reallyafile.open("something.txt");
...
see full examples on this site in the reference.