You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++初学者求代码总结:元音与数字计数程序逻辑练习

你的C++元音与数字统计程序总结

Hey there! Let's walk through your beginner-friendly C++ program to break down what it does, how it works, and note a few details that might help you as you keep learning.

核心功能

This program counts the number of case-insensitive vowels (a, e, i, o, u) and digits in user input. It stops processing as soon as it encounters the # character, and accepts input that can be a single word or other content (though there's a small caveat we'll mention later).

代码分步解析

1. 基础设置

  • You included the <iostream> header to use input/output operations, then imported specific std members (cout, cin, endl) so you don't have to write std:: every time.
  • The program starts with main() (note: for standard C++, this should be int main() to return an integer status code, but your version still works in most compilers).

2. 变量与输入处理

  • You declared a char str[100] array to store up to 100 characters of user input.
  • cin >> str reads input from the user, but keep in mind: this stops reading at the first whitespace (space, tab, newline). So if you input something like hello world#, it will only process hello.

3. 计数逻辑

  • You created individual integer counters for each vowel (count_a, count_e, etc.) and one for digits (count_digit), plus a loop index i to traverse the input string.
  • The while loop runs as long as the current character (str[i]) is not # and not the string terminator \0 (which marks the end of the input string).
  • Inside the loop, you grab each character with char input = str[i], then use a switch statement to categorize it:
    • Case labels group uppercase and lowercase vowels together to increment the corresponding counter.
    • All digits (0-9) are grouped to increment count_digit.
    • Any other character hits the default case and is ignored.
  • After checking each character, you increment i to move to the next one in the string.

4. 结果输出

Finally, the program prints out the count for each vowel and the total number of digits using cout.

示例运行

Input: aaAeeeghjfh12iOu#12qea
Output:

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

This matches exactly what you'd expect: the program stops at #, so the characters after it aren't counted.

小优化建议(适合初学者进阶)

  • To handle input with spaces, replace cin >> str with cin.getline(str, 100) — this reads until a newline instead of whitespace.
  • Instead of individual vowel counters, you could use an array or a single total vowel count if you don't need to track each vowel separately, but your current approach is great for clarity when learning.
  • Always use int main() instead of main() to follow C++ standards.

内容的提问来源于stack exchange,提问作者user13493679

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:17:38