类型:转载 责任编辑:asp 日期:2007/03/01
#include <iostream.h>
void main()
{
char c;
int nother=0,ndigit[10];
for (int i=0;i<10;i++)
ndigit[i]=0;
cin >>c;
while (c!=$)
{
switch(c)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9: ++ndigit[c-0]; break;
default: ++nother;
}
cin >>c;
}
cout <<"digiter=";
for (i=0;i<10;i++)
cout <<ndigit[i] << ;
cout <<"\nother=" <<nother <<endl;
}
为什么++ndigit[c-0]中,为什么一定要有个c-0 ? 有它结果就对,没它结果就不对。为什么?谢谢大家了
推荐阅读
你输入的是字在程序里是char型的,为了转化成 int的就用c减字符‘0’,在ascii码中‘0’是一个数,‘0’+1就是‘1’。
这一串case好丑陋!
while (c!=$)
{
if(isdigit(c))
++ndigit[c-0];
else
++nother;
cin >>c;
}
c 里面的转换有自动和强制完成的.
++ndigit[c-0] 中c-0用于数组检索,应该符合数组的下标表示范围.
c-0是数还是字符看你用在什么地方,++ndigit[c-0]中数组下标需要整数,所以c-0转化成整数.如果这样写
char ch = c-0;则ch是c-0对应的整数对应的ascii码.
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <cstdlib>
using namespace std;
struct calculate {
int& m_other;
int* m_digit;
calculate(int& other, int* digit) : m_other(other), m_digit(digit) {}
int operator()(char c) {
if(isdigit(c))
++m_digit[c - 0];
else
++m_other;
return c;
}
};
int main()
{
int nother=0,ndigit[10] = {0};
string s;
cin >> s;
for_each(s.begin(), s.end(), calculate(nother, ndigit));
cout <<"digiter=";
copy(ndigit, ndigit + 10, ostream_iterator<int>(cout, " "));
cout <<"\nother=" <<nother <<endl;
system("pause");
return 0;
}
如果想把空格字符也统计在内,将
cin >> s;
改成:
getline(cin, s);