Hi,
I want to count the number of characters in a text file and want to sore them in an array.(Remember its a file not a string).Thanxx
Hi,
I want to count the number of characters in a text file and want to sore them in an array.(Remember its a file not a string).Thanxx
Okay,
* Open the file
* Move the pointer to the end of the file, and get it's position (ie fseek() and ftell()) Which will tell you it's size in bytes
* Allocate a buffer on the heap (ie, dynamically allocated), big enough to hold the file
* Read the file into the buffer
* Close the file
* Post your problems here, at least have a crack at it! (Sounds like homework to me!)
Something I wrapped up that should work..
Code:#include <iostream> #include <fstream> #include <string> const std::string file = "filename.txt"; // string that is going to contain the file's contents std::string str = ""; int main(void) { // construct a datastream named fin to the specified file std::ifstream fin(file.c_str(), std::ios_base::in); // return false if the function couldn't write to file if (!fin.is_open()) fin.clear(); // temp variable used to contain each char char ch; // variable that counts each character in the file int count = 0; // loop trough each character in the file while (fin.get(ch)) { count++; str+=ch; } // show the amount of characters in the file std::cout << count; // show the contents which is stored in the std::string 'str' std::cout << std::endl << str; // close file output stream fin.close(); return 0; }
How about a vector instead?
This loads a file into a vector of char. The length of the file can be found by calling this vector's size() method.Code:#include <algorithm> #include <iterator> #include <fstream> #include <iomanip> #include <string> #include <vector> std::vector<char> load_file(const std::string &name) { std::vector<char> output; std::ifstream input(name.c_str()); input >> std::noskipws; std::copy(std::istream_iterator<char>(input), std::istream_iterator<char>(), std::back_inserter(output)); return output; }
Thanxx buddies,
Now i got it ,but i do not want to keep the spaces in my array.I mean i want to ignore the spaces and store the next character in the array instead of space.
store the next character in a temporary char and check if its a space
if its not, add it to the array
OS: Windows 7, XUbuntu 11.10, Arch Linux
IDE: CodeBlocks
Compiler: GCC