首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

统计一个文本中的单次数量,为啥结果总是0

2013-11-29 
统计一个文本中的单次数量,为何结果总是0?这里把单词定义为被两个A类字符所包围的字符串。这里我想不用任何

统计一个文本中的单次数量,为何结果总是0?
这里把单词定义为被两个A类字符所包围的字符串。这里我想不用任何高级技能,具体就是不使用string,直接用char来解决。可是我的统计结果一直是0.这个是为什么呢?

这个是文本Sample Text.txt中内容:
One, two, three, four, five
Six, seven, eight, nine, ten.
Eleven,Twelve,Thirteen,Fourteen.
Iwant to change the world.


程序的代码如下,很简单,应该不需要说明吧:


// counting the words in a file, without using any advanced techniques.

#include <iostream>
#include <fstream>

inline void keep_window_open()
{
using namespace std;
cout<<"\nPress any key to exits:\n";
getchar();
}

int main()
{
using namespace std;
ifstream infile("Sample Text.txt");
if(infile.fail())
{
cerr<<"\nNo open-file found!\n";
return -1;
}
unsigned words_count=0, letters_count = 0;
bool found_word=true;
char letter;
while(infile >> letter)
{
if(letter == ' ' || letter == '\n')
{
if(found_word == false)
{
++words_count;
found_word = true;
}
}
else
found_word = false;

++letters_count;

}
cout<<"\nSo we have found "<<words_count<<" words in the text.\n";
}
string 统计 单词
[解决办法]
检查letter值是什么
[解决办法]
帮你修改了一下。首先可以用infile.get()函数来获得任意的字符(包括空格);其次用isspace()函数来判断是否是空白字符比较好(比较全面)。



// counting the words in a file, without using any advanced techniques.

#include <iostream>
#include <fstream>

inline void keep_window_open()
{
using namespace std;
cout<<"\nPress any key to exits:\n";
getchar();
}

int main()
{
using namespace std;
ifstream infile("Sample Text.txt");
if(infile.fail())
{
cerr<<"\nNo open-file found!\n";
return -1;
}
unsigned words_count=0, letters_count = 0;
bool found_word=true;
char letter;
while(infile.get(letter))
{
if(isspace(letter))
{
if(found_word == false)
{
++words_count;
found_word = true;
}
}
else
found_word = false;

++letters_count;

}
cout<<"\nSo we have found "<<words_count<<" words in the text.\n";
}

热点排行