我可以总结一下这个c ++程序???这是元音和数字的计数循环

问题描述 投票:0回答:2

我是C ++的初学者。我开发了一个程序,但我想比较一下,尝试总结以下代码来练习我的逻辑技能。

该程序当前正在运行。该程序对在用户输入中找到的元音和数字进行计数。输入通常必须是一个单词,但可以是随机的。这里的特殊部分是,当识别出“#”时,程序将停止计数。

#include <iostream>

using std::cout;
using std::cin;
using std::endl;



main () { 
  char str[100];
  cin>>str;

 //Declaring values depending of the letter 
  int count_a = 0;
  int count_e = 0;
  int count_i = 0;
  int count_o = 0;
  int count_u = 0;
  int count_digit = 0; 

  int i = 0;
    while (str[i] != '#' && str[i] != '\0') {
  //for(int i = 0; (str[i] != '#' && str[i] != '\0' ) ; i++) { //This loop is working identifyng one of the places of each 


   char input = str[i]; //Get character for character
    switch(input){
//letter a      
    case 'a':
    case 'A':       
    count_a++;
    break;
//letter e  
    case 'e':
    case 'E':   
    count_e++;
    break;  
//letter i
    case 'i':
    case 'I':   
    count_i++;
    break;
//letter o      
    case 'o':
    case 'O':   
    count_o++;
    break;
//letter u
    case 'u':
    case 'U':   
    count_u++;
    break;  
//digit
    case'1':
    case'2':
    case'3':
    case'4':
    case'5':
    case'6':
    case'7':
    case'8':
    case'9':
    case'0':    
   count_digit++;
    break;
    default:
    break;
    }
i++;
  }

   cout <<"a="<<count_a<< endl;
   cout <<"e="<<count_e<< endl;
   cout <<"i="<<count_i<< endl;
   cout <<"o="<<count_o<< endl;
   cout <<"u="<<count_u<< endl;
   cout << "Digit="<<count_digit<< endl;
  return 0;
  }

例如,如果我写aaAeeeghjfh12iOu#12qea,我的输出将是:

a = 3 e = 3 i = 1 o = 1 u = 1 Digit = 2

c++ arrays loops count switch-statement
2个回答
0
投票

如果问题是如何根据代码行来缩短程序,您可以使用if / else语句代替case语句:

示例:

case'1': case'2': case'3': case'4': case'5': case'6': case'7': case'8': case'9': case'0':

可以简化检查的内容

input >= '0' && input <= '9'

0
投票

您可以使用数组存储所有计数,然后仅打印您感兴趣的值:

#include <array>
#include <cctype>
#include <climits>
#include <cstdio>
#include <iostream>
#include <numeric>
#include <string>
#include <string_view>

int main() {
  std::string str;
  std::cin >> str;

  std::array<int, UCHAR_MAX> characters{};

  for (auto const ch : str) ++characters[static_cast<unsigned>(ch)];

  using namespace std::literals;
  for (unsigned char const ch : "aeiou"sv)
    std::printf("%c = %d\n", static_cast<char>(ch),
                characters[std::tolower(ch)] + characters[std::toupper(ch)]);

  std::printf("Digits = %d\n",
              std::accumulate(&characters['0'], &characters['9'] + 1, 0));
}

了解更多:

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