If you have access iostream (or the entire STL for that matter), it is a simple matter of using ifstream. Using ifstream, you can read in one word at a time and check to see if a word is a palidrome. The following would probably do it: (except check for palidromeness)
Code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int isPalidrome (string aWord) {
// Your code here
}
int main (int argc, char * argv[]) {
ifstream inFile ("path/to/file.txt");
string aWord;
int numPalidromes = 0;
if (!inFile.is_open()) {
cout << "Error opening file!\n";
return -1;
}
inFile >> aWord;
while (!inFile.eof()) {
if (isPalidrome(aWord))
numPalidromes++;
inFile >> aWord;
}
cout << numPalidromes << endl;
return 0;
}
Since C/C++ considers any whitespace to be a delimiter, it wouldn't matter if you had one word per line, or 100 words per line, as long as they are separated by some whitespace. When you say inFile >> aWord, it is the same thing as cin >> aWord, except that it is retrieving it from a file instead of stdin. Getting an entire line is a bit trickier, but since you don't need to do that, I won't cover it here.
The fstream class is the abstraction later on top of the OS to allow you to read and write from files. C++ is nice in this respect.
If you are not using C++, and instead are using straight C, the matter is a bit more difficult. Again, the same principle applies for whitespace, except it is a different set of functions to get data from the file. Furthermore, you have to work with char * instead of strings. The following should work (again, checking for palidromes is an exercise for the reader).
Code:
#include <stdio.h>
#define MAX_LEN 256
int isPalidrome (char * aWord) {
/* Your code here */
}
int main (int argc, char * argv[]) {
FILE * fileHandle;
char word[MAX_LEN];
int numPalidromes = 0;
fileHandle = fopen ("/path/to/file", "r");
if (!fileHandle) {
printf ("Error opening file!\n");
return -1;
}
fscanf(fileHandle, "%s", word);
while (!feof(fileHandle)) {
if (isPalidrome(word)) numPalidromes++;
fscanf(fileHandle, "%s", word);
}
fclose (fileHandle);
printf ("%d\n", numPalidromes);
return 0;
}
That should do it for C. To open files and such in C you use the stdio routines located in stdio.h. It is a much more 'low level' way of doing things, but does work.
This code has been tested to compile on linux (gcc 3.3.3).
Good luck!
-Ted