I am very new to C programming.
How could I write a C program that could count the characters, words, spaces, and punctuations in a text file?
Any help will be really appreciated. I am doing this as part of my C learning exercise.
Thanks,
Ajay
I am very new to C programming.
How could I write a C program that could count the characters, words, spaces, and punctuations in a text file?
Any help will be really appreciated. I am doing this as part of my C learning exercise.
Thanks,
Ajay
I hope this is not homework.
#include <ctype.h> defines the functions and macros you need.
isspace() spaces (include newlines)
ispunct() punctuation characters
isalnum() regular characters A-z a-z plus digits 0-9
2 use fgets to read a line
while you get a line of text
3. interate over all of the chacters you just read in - checking char types with those
functions
end while
close the file
use printf to display all of the results. word count per line == # of isspace() characters you find on the line, so it also equals the total words. This assumes only single spaces between characters. And no leading spaces on a line.
If this is not homework then post here what you have tried to code so far...
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string lineBuffer;
ifstream inMyStream ("c:/File.txt");
if (inMyStream.is_open()) {
int count = 1;
while (!inMyStream.eof() ){
getline (inMyStream, lineBuffer);
cout << count << lineBuffer << endl;
count++;
}
inMyStream.close();
}
else cout << "File Error: Open Failed";
return 0;
}
but, that is where i got stuck.
/use this to count words/
#include <stdio.h>
#define IN 1 /* inside a word*/
#define OUT /outside a word/
int
main(void)
{
int nw, state;
state = OUT;
while((c= getchar()) != EOF){
/*think using something here for punctuations*/
/*for char count*/
if\(c == ' ' || c == '\\n' || c == '\\t'\)
state = OUT;
else if \(state == OUT\)\{
state = IN;
\+\+nw;
\}
}
return 0;
}
/see it and try to implement otherway/