Count number of letters in a word from a file
Mar 26, 2016 at 3:33am UTC
Hello,
I need to make a program that reads each word from a file and replaces the word with the number of its letters and prints it in an output file.
The program works, but in the output each punctuation character shows as "0".
For the words "Hello, my name is." instead of "5 2 4 2" I receive "5 0 2 4 2 0".
I thought the reason was the while statement, but I am not sure anymore.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
Put the code you need help with here.#include <fstream>
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
int count = 0;
char ch;
ifstream infile;
ofstream outfile;
infile.open("input.txt" , ios::in);
if (!infile)
{
cerr << "The file input.txt could not be opened" << endl;
exit(1);
}
outfile.open("output.txt" , ios::out);
if (!outfile)
{
cerr << "The file output.txt could not be opened" << endl;
exit(1);
}
while (infile)
{
infile.get(ch);
for (count = 0; ch != ' ' && (isalpha(ch)); count++)
{
infile.get(ch);
}
outfile << count << " " ;
count = 0;
}
infile.close();
outfile.close();
return 0;
}
Last edited on Mar 26, 2016 at 3:57am UTC
Mar 26, 2016 at 1:36pm UTC
Change line 33:
1 2
if (count > 0)
outfile << count << " " ;
Mar 26, 2016 at 1:55pm UTC
Your program will go into an infinite loop if the last input character is a letter.
The test for ch != ' ' on line 29 is redundant. If isalpha(ch) is true then it won't be a space.
You can solve these problems by having just one call to get(). Here is a version that reads/write using cin and cout. This also copies the newlines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;
int main()
{
int count = 0;
char ch;
while (cin.get(ch)) {
if (isalpha(ch)) {
++count;
} else if (count) {
cout << count << ' ' ;
count = 0;
}
if (ch == '\n' ) {
cout << '\n' ;
}
}
return 0;
}
Mar 27, 2016 at 6:17pm UTC
Thank you. When I added "if (count > 0)" everything worked right.
Topic archived. No new replies allowed.