计算文本输入中特定字符的频率
Count the frequency of a specific character in a text input
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
相关文章:
- C++字符*缓冲区的大小
- HEX值到wchar_t字符(UTF-8)的转换
- 为什么 Serial.println(<char[]>);返回随机字符?
- 我的字符计数代码计算错误.为什么
- 字符串-C++后显示的随机字符
- 芬威克树(BIT).找到具有给定累积频率的最小索引,单位为 O(logN)
- 将Integer转换为4字节的unsined字符矢量(按大端字节顺序)
- 如何在C++中从字符串中分割字符
- 为什么msgrcv()将垃圾字符馈送到缓冲区
- 跟踪多个文件中一系列字符的频率
- 字符串中字符的最大频率
- 如何将字符设置为函数?我对语法感到困惑...设置<char>max_freq(映射<字符,整数>频率)
- 在最少的操作中实现字符串所有字符的相同频率。(所有字符的范围从'a'到"z")
- 哪种方法更适合霍夫曼编码 我想读取字符及其频率
- 计数字符串C 中字符的频率
- C++:输出文件中ASCII字符计数频率的结果时出现的奇怪数字
- C++:计算文件中ASCII字符的频率
- 计算文件中字符的频率.C++
- 计算文本输入中特定字符的频率
- 字符频率重复和重置问题