2
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;
}

また、すべての句読点でカウントを停止する必要があります。正しいカウントを得ることができないようです。

4

4 に答える 4

2

それはあなたの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.
于 2013-10-01T23:48:58.200 に答える
0

あなたのプログラムにはいくつかの疑わしい点があります:

  char sentence;
  cin >> sentence;

これは、1文字しか読み取っていないように見えます。getline() して、ユーザー入力を std::string に保存したい場合があります

はどうかと言うと

  while ( sentence == b || B ) {

b と B は未定義であるため、これはコンパイルさえしません。多分それはあるべきです

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

ここで、cur_byte は文字列内で適切に管理されたイテレータです

于 2013-10-01T23:48:07.947 に答える
0
#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--;
}

幸運を ;)

于 2013-10-01T23:48:21.410 に答える
0
#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;
}

例:

文を入力してください: Two B or not two b, それが質問 Bb.

bの数: 2

于 2013-10-02T00:50:14.497 に答える