Pangrams

Description:

The sentence ‘A quick brown fox jumps over the lazy dog’ contains every single letter in the alphabet. Such sentences are called pangrams. You are to write a program, which takes a sentence, and returns all the letters it is missing (which prevent it from being a pangram). You should ignore the case of the letters in sentence, and your return should be all lower case letters, in alphabetical order. You should also ignore all non US-ASCII characters.In case the input sentence is already a pangram, print out the string NULL
Input sample:

Your program should accept as its first argument a filename. This file will contain several text strings, one per line. Ignore all empty lines. eg.

A quick brown fox jumps over the lazy dog
A slow yellow fox crawls under the proactive dog

Output sample:

Print out all the letters each string is missing in lowercase, alphabetical order .e.g.

NULL
bjkmqz

My solution

#include <fstream>
#include <string>
#include <algorithm>
#include <iostream>

struct InvalidChar {
    bool operator()(char c) const {
        return !isprint((unsigned)c);
    }
};

void print_missing_pangrams_chars(std::string &line) {
	bool found = true;
	std::transform(line.begin(), line.end(), 
		           line.begin(), ::tolower);

	std::sort(line.begin(), line.end());

	line.erase(std::remove_if(line.begin(),
		                      line.end(),
							  InvalidChar()), 
							  line.end());

	std::string dictionary = "abcdefghijklmnopqrstuvwxyz";
	for ( std::string::iterator itr = dictionary.begin();
		itr != dictionary.end();++itr) {
			if (line.find(*itr) == std::string::npos){
				std::cout << *itr;
				found = false;
			}
	}
	if ( found )
		std::cout << "NULL";
	std::cout << std::endl;
}
int main ( int argc, char **argv) {
    std::ifstream inpFile(argv[1]);
    if ( inpFile.peek() == EOF ){
        return -1;
	} 
    std::string line; 
    if (inpFile.is_open()) {
        while (! inpFile.eof() ) {               
            std::getline (inpFile,line);
			if ( !line.empty()) {
				print_missing_pangrams_chars(line);
			}
        }
        inpFile.close();
    }
	return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s