计算文本输入中特定字符的频率

Count the frequency of a specific character in a text input

本文关键字:字符 频率 文本 输入 计算      更新时间:2023-10-16
int main()
{
  char sentence;
  int count;
  cout << "Enter sentence: ";
  cin >> sentence;
  count = 0;
  while ( sentence == 'b' || 'B' ) {
    count++;
  }
  cout << "Number of b's: " << count * 1 << endl;
  return 0;
}

计数也必须停止在所有标点符号处。我似乎无法让它给我正确的计数。

这是

你的while循环。 变量sentence在循环内不会更改,因此循环可能会永久执行。

您可能希望对句子使用 std::string,对句子中的字符使用 char

编辑 1:示例

char letter;
cout << "Enter a sentence:n";
while (cin >> letter)
{
  // Check for sentence termination characters.
  if ((letter == 'n') || (letter == 'r') || (letter == '.'))
  {
    break; // terminate the input loop.
  }
  // Put your letter processing code here.
} // End of while loop.

程序中有几个可疑点:

  char sentence;
  cin >> sentence;

这看起来只是在读取一个字符。您可能希望获取 line() 并将用户输入保存在 std::string 中

至于

  while ( sentence == b || B ) {

这甚至不会编译,因为 b 和 B 是未定义的。也许应该是

  if ( cur_byte == ‘b' || cur_byte == ‘B’ )
     count++

其中cur_byte是字符串中一些正确维护的迭代器

#include <string>

使用字符串。 string sentence; 并创建一个长:

for(int i=0; i<sentence.length(); i++)
if(sentence[i] == b || B) count ++;

如此简单的;)祝你好运;)

编辑 1:
如果您只使用while

int count = sentence.length();
int count2 = 0;
while(count != 0)
{
if(sentence[count] == b||B) count2++
count--;
}

祝你好运;)

#include <iostream>
using namespace std;
int main()
{
    char c;
    int n = 0;
    cout << "Enter sentence: ";
    while (cin >> c && !ispunct(c)) if (tolower(c) == 'b') n++;
    cout << "Number of b's: " << n << endl;
    return 0;
}

例:

输入句子:两个B还是不是两个B,这就是问题Bb。

b的数量:2