Re: Simple Counting Program
Maybe there is a better way to do this, but this is just one way I thought of:
Code:
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
int main () {
string s;
int totalChars = 0,
totalWords = 0,
totalLines = 0;
ifstream in("test.txt");
if(!in){
cout << "Failed to open input file.";
return -1;
}
while(getline(in, s, '\n')){
totalChars += s.length();
totalLines++;
for(int i = 0; i < s.length(); i++){
if(s[i] == ' ')
continue;
totalWords++;
while(i != s.length() && s[i] != ' ')
i++;
}
}
cout << "Total Words: " << totalWords << endl;
cout << "Total Characters: " << totalChars << endl;
cout << "Total Lines: " << totalLines << endl;
return 0;
}