我正在尝试学习一些编码来扩大我的知识范围,而且我似乎遇到了一些难题。字数统计 - 忽略/减去双倍空间
我想创建一个程序来输出从文件中读入的字符,数字,标点符号,空格,单词和行的数量。
这里是文本文件,我在读
See Jack run. Jack can run fast. Jack runs after the cat. The cat's fur is black. See Jack catch the cat.
Jack says, "I caught the cat."
The cat says, "Meow!"
Jack has caught 1 meowing cat. Jack wants 5 cats, but can't find any more.
这里是我的代码
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream lab3;
string word;
lab3.open("lab3.txt");
int countletters=0,countnum=0,countpunc=0,countspace=0,words=0,line=0;
char character;
if(!lab3)
{
cout << "Could not open file" << endl;
return 1;
}
while(lab3.get(character) && !lab3.eof())
{
if(isalpha(character))
{
countletters++;
}
if (isdigit(character))
{
countnum++;
}
if (ispunct(character))
{
countpunc++;
}
if (isspace(character))
{
countspace++;
}
if (isalpha(character) && (isspace(character++) || ispunct(character++)))
{
words++;
}
if(character=='\n')
{
line++;
}
}
cout << "There are " << countletters << " letters." << endl;
cout << "There are " << countnum << " numbers." << endl;
cout << "There are " << countpunc << " punctuations." << endl;
cout << "There are " << countspace << " spaces." << endl;
cout << "There are " << words << " words." << endl;
cout << "There are " << line << " sentences." << endl;
lab3.close();
return 0;
}
输出:
There are 167 letters.
There are 2 numbers.
There are 18 punctuations.
There are 52 spaces.
There are 0 words.
There are 4 sentences.
有些事情我希望学习:
- 一个解释为什么字数不起作用,并替换考虑双空格的工作代码。
- 对我的学习目的/效率的代码进行改进的建议。
- 从文本文件中读取信息的说明。无论你的字母,数字,标点符号是什么,都可能会遇到这种类型的编码。
有些事情我是知道的:
using namespace std;
是不是好的做法 - 什么是真实世界应用的最佳实践。- 我是一个初学者,这可能不是绝对不是作物编码的奶油提前
`谢谢你的帮助和建议:)
不知道其他的东西,但添加命名空间之前的单词像:std :: string更好,因为不同的命名空间可以使用相同的单词。 /建议改进我的学习目的/效率的代码/应该在codereview(http://codereview.stackexchange.com/)上询问 –
为什么'character'增加了,更不用说隐藏在'if '? – chris
你的输出是什么,你期望得到什么? –