计算字母/数字的数量

问题描述 投票:-1回答:2

我的目标是编写一个可以读取文本文件的C ++程序,并且:

  • 计算平均字母/句子数。
  • 计算总位数。

将使用命令“./a.out <textfile”读取文本文件

到目前为止我所尝试的是让程序一次用“cin >> current”检查每个字符。我有一个循环。如果当前点击一个标点符号,它应该将linecount增加1.它也应该是读取字母字符,但我不知道如何计算它们。

#include <iostream>
#include <iomanip>
#include <cmath>
#include <cctype>
using namespace std;
int main()
{
  int letters; //Total number of letters per sentence                                                                                                                              
  int digits; //Total number of digits                                                                                                                                             
  int sentencecount; //Number of sentences                                                                                                                                         
  float averageletters; //Average number of letters per sentence                                                                                                                   
  int linecount ; //Count of lines                                                                                                                                                 
  char current; //Current character                                                                                                                                                

  cin >> current;

  digits = 0;
  letters = 0;
while (cin)
    {
      if (current == '.' == '!' == '?')
          linecount++;
          //calcuate averages and other sentence data                                                                                                                              
          //reset sentence data                                                                                                                                                    
          if (isalpha(current))//repeat for digits                                                                                                                                 
        letters++;
          cout << "line #" << letters << endl;
        cin >> current;
    }                                                          

  return 0;
}
c++
2个回答
3
投票
if (current == '.' == '!' == '?')

上面的这行不符合你的想法。假设current是一个感叹号。然后评估为:

if (false == '!' == '?') // The character is NOT a '.'

然后:

if (false == '?') // '!''s value is > 0, so the condition checks if true == false

最后:

if (false) // For the same reasons as above

要修复您的病情,请使用:

if (current == '.' || current == '!' || current == '?')

这使用布尔OR运算符来检查语句中的任何条件是否为真,在这种情况下进入if语句。您还可以在条件中添加括号以提高可读性。


0
投票

if(current =='。'=='!'=='?')

可能不会评估他们的意图。您可能想要了解c ++运算符优先级。

你可以尝试 -

if((current =='。')||(current =='!')||(current =='?'))

© www.soinside.com 2019 - 2024. All rights reserved.