Reading white spaces....

Hi,

Here's my situation.I'm reading a file that consists of characters including white space.Once I read them I'm counting the occurrences of each character.This means I need to count occurrences of white space as well.If I use ifstream I skip the white spaces and I dunno the filesize so I cant use getline.What do I do?
You need to use the unformatted input functions, such as read.
You can either read 1 character at a time and count, or read a block into a buffer then count the characters in the buffer (more efficient as less I/O). If doing the latter you will need to use gcount to find out how many characters you did read when you reach end of file.
See http://www.cplusplus.com/reference/iostream/ifstream/ for info on the various functions, etc.
I think you can do it with the getline function fine... The getline stops at the end of the line, only if you use the ">>" operator stops at white space.

I did it like that:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;

int main(){
   fstream inText( "text.txt", ios::in );
   string line, file;
   while( getline( inText, line ) )
      file += line + '\n';
   cout << "White spaces: " << count( file.begin(), file.end(), ' ' );
}


Hope this helps

[EDIT]: Something else I just thought about.
If you don't wont to store all the file in a string (because of ram) then you can use a map ( <char, int> ) and read each letter and store it in there.
Last edited on
^Too slow. read() byte by byte and increment the elements of an unsigned[256].
Last edited on
What about the map?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <fstream>
#include <map>
using namespace std;

int main(){
   fstream inText( "text.txt", ios::in );
   map<char, int> chars;
   char ch;
   //Count letters
   while( ( ch = inText.get() ) && inText.good() )
      ++chars[ch];
   //Display counted letters
   for( map<char, int>::iterator it = chars.begin(); it != chars.end(); ++it )
      if( it->first == '\n' )
         cout << "New lines: " << it->second << " times\n";
      else
         cout << "'" << it->first << "'" << ": " << it->second << " times\n";
}


I did understand what you said but I was wondering which one is better...
Maps take O(log n) time to return a reference to an element. Arrays take O(1) time.

Ask this question: "is my map using integral, consecutive keys? Should every key always be present?"
If this is the case, use an array.
Last edited on
that's good to know, thanx
Topic archived. No new replies allowed.