如何读取和计数输入文件中的单词,计数和打印每个单词的字母数量
How to read and count the words in an input file, count and print the amount of letters per word using C++?
我是一个编程新手,有一项任务要求我创建一个程序,该程序将读取一个包含单词列表的文本文件,计算单词总数和每个单词的字母数量,并打印出一个输出文件,该文件按类别从1个字母单词到13个字母单词的单词数量为x个字母。
当我创建我的函数并尝试让它读取文本文件中的单词时,它不允许我使用inFile >> word;
读取它们的长度。
我得到错误:
"二进制表达式的无效操作数".
其他同学使用这个命令没有麻烦。我在OS X El Capitan上使用Eclipse Mars.1。
我得到的另一个错误是在我的开关功能上,它对第一种情况进行评估,但对以下情况不进行评估。在这种情况下,我得到以下错误消息:
" 'case'语句不在Switch语句上".
提前感谢!
void Words_Statistics(std::ifstream & fin, std::ofstream & fout, std::string inFile, std::string outFile)
{
// Variable Declaration
inFile="words.txt";
outFile="Words_Satistics.txt";
string word;
int totalWords=0;
int lettersQuantity;
int un, deux, trois, quatre, cinq, six, sept, huit, neuf, dix, onze, douze, treize, otre;
un = deux = trois = quatre = cinq = six = sept = huit = neuf = dix = onze = douze = treize = otre=0;
// Open input file to read-in
fin.open(inFile);
if(fin.fail())
{
cout << inFile << " Failed to open file."<< endl;
exit (1);
}
do {
(inFile >> word);
lettersQuantity = int (sizeof(word));
totalWords++;
lettersQuantity+=lettersQuantity;
switch (lettersQuantity)
case 1:
un++;
break;
case 2:
deux++;
break;
case 3:
trois++;
break;
case 4:
quatre++;
break;
case 5:
cinq++;
break;
case 6:
six++;
break;
case 7:
sept++;
break;
case 8:
huit++;
break;
case 9:
neuf++;
break;
case 10:
dix++;
break;
case 11:
onze++;
break;
case 12:
douze++;
break;
case 13:
treize++;
break;
default:
otre++;
break;
}
while (!fin.eof());
int avg = lettersQuantity / totalWords;
}
这里inFile >> word
, inFile
和word
是std::string
,因此对它们应用operator>>
是没有意义的(毕竟你不能右移字符串,这会产生意想不到的结果:))。
您可能指的是fin >> word
,其中fin
是您打开的文件:)
switch
语句需要括号:
switch (lettersQuantity)
{ //Note bracket
case 1: //....
//....
}
在一个无关的注意,sizeof(word)
不做你认为它做什么。它获得word
的实际大小,而不是word
的字符数量。您可以使用word.length()
:)
相关文章:
- 按单词搜索文件,然后在C++中打印特定行数
- 如何打印 BFS 路径本身而不是此单词梯的路径长度?
- 用最少的元音打印单词
- 延迟逐个字符打印单词
- 我的控制台正在打印随机单词以及没有执行正确的数学运算
- 如何在 STL 中使用reverse_iterator打印单词
- 如果该行包含特定单词 (C++),请打印该行
- 用句子从单词打印单词
- 打印所有可能有 4 个字母的单词的时间太多
- 打印出使用地图实现的Trie中的所有单词
- 如何在带有给定特定前缀的向量中打印出单词
- 使用Trie打印所有字典的单词
- (C++) 打印字符数组字符串的单词时出现问题
- 动态分配的数组C 读取句子并打印单词
- 如何将消息发送到缓冲区并反向打印前三个单词的消息
- 打印以 "a" 开头的单词(字符串中)
- 打印由用户定义的数组,第一个数字确定单词的大小,第二个数字确定行的大小
- 如何在单词中打印元音
- 从结构上打印单词
- 如何从.txt文件复制单词到数组.然后将每个单词打印在单独的一行上