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 specificstdmembers (cout,cin,endl) so you don't have to writestd::every time. - The program starts with
main()(note: for standard C++, this should beint 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 >> strreads input from the user, but keep in mind: this stops reading at the first whitespace (space, tab, newline). So if you input something likehello world#, it will only processhello.
3. 计数逻辑
- You created individual integer counters for each vowel (
count_a,count_e, etc.) and one for digits (count_digit), plus a loop indexito traverse the input string. - The
whileloop 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 aswitchstatement 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
defaultcase and is ignored.
- After checking each character, you increment
ito 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 >> strwithcin.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 ofmain()to follow C++ standards.
内容的提问来源于stack exchange,提问作者user13493679

