c++ 4.17 LAB: Count characters Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string. The output should include the input character and use the plural form, n's, if the number of times the characters appears is not exactly 1. Ex: If the input is: n Monday the output is: 1 n

Respuesta :

Answer:

#include <iostream>

using namespace std;

int main() {

   int n = 0;

   char c;

   string str;

   cin >> c >> str;

   for (int i = 0; i < str.length(); ++i)

       if (c == str[i]) n++;

   cout << n << " n" << (n > 1 ? "'s" : "");

   return 0;

}

Explanation:

Declares variables n, c, and str.

Next a loop lets count number of character c in string str.

Finally, answer is showing.

The complete code of the given program is provide below in the explanation segment.

Program explanation:

  • Header files.
  • Main function.
  • Variable declaration.
  • Find the number of times letter appears.
  • If statement.
  • Return 0.

Program code:

#include <stdio.h>

#include <string.h>  

int main()

{

  char c;

  char s[50];

  int temp = 0, i;

  //Read input

  scanf(" %c", &c);

  scanf("%s", s);    

  for (i = 0; i < strlen(s); ++i)

{

      if (s[i] == c)

{

          ++temp;

      }

  }  

  if(temp!=1)

      printf("%d %c's\n", temp,c);

  else

      printf("%d %c\n", temp,c);

  return 0;

}

Output:

The attachment is provide below.

Learn more:

https://brainly.com/question/23254166

Ver imagen Cricetus