用visual studio,使用while语句,对输入字符的字母个数和数字个数进行统计
时间: 2023-05-31 11:03:38 浏览: 89
以下是使用C++语言在Visual Studio中实现输入字符的字母个数和数字个数进行统计的代码:
```cpp
#include <iostream>
using namespace std;
int main()
{
char ch;
int letter_count = 0, digit_count = 0;
cout << "请输入字符串(以“#”结束):" << endl;
cin.get(ch);
while (ch != '#')
{
if (isalpha(ch)) // 判断是否为字母
letter_count++;
else if (isdigit(ch)) // 判断是否为数字
digit_count++;
cin.get(ch);
}
cout << "字母个数为:" << letter_count << endl;
cout << "数字个数为:" << digit_count << endl;
return 0;
}
```
程序首先提示用户输入字符串,并使用`cin.get(ch)`函数逐个读取输入的字符。在while循环中,使用`isalpha(ch)`函数判断字符是否为字母,若是则字母个数加1;使用`isdigit(ch)`函数判断字符是否为数字,若是则数字个数加1。当读取到“#”字符时,循环结束,程序输出字母个数和数字个数。
注意:在使用`isalpha(ch)`和`isdigit(ch)`函数时,需要在程序的开头添加`#include <cctype>`头文件。