I have an assignment where i need to count lines, words and characters from a file. I'm having a problem counting the right amount of characters and words since if it gets doubled space it counts like a character and a word.
the output should be
Example
lines words characters filename
3 5 29 testfile
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <iomanip>
using namespace std;
int main(int argc, const char * argv[]) {
string lines, words, chars, file1, file2;
ifstream infile;
ofstream outfile;
char c;
int countLines = 0;
int countChars = 0;
int countWords = 0;
cout<< "Enter the file name" << endl;
cin >> file1;
infile.open(file1.c_str());
while(!infile.eof())
{
if(infile.peek() == 1)
break;
c = infile.get();
if(c != '
')
countChars++;
else
countLines++;
if(c == ' '|| c =='
')
countWords++;
}
// countChars = countChars - countWords;
cout << setw(12) << countLines << setw(12) << countWords << setw(12) << countChars << endl;
infile.close();
return 0;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…