【发布时间】:2019-12-17 12:46:40
【问题描述】:
所以,我基本上认为我已经弄清楚了这个小程序 - 我正在尝试制作一个程序,该程序具有查看用户输入的内容并计算用户输入的整数的数量,例如所以:
void finish(int a, char *b, int c);
int main()
{
int i=0;
int numb=0;
char phrase[30];
printf("This program will count the amount of \nnumbers in an entered phrase.\n");
printf("Please enter your phrase: ");
gets(phrase);
finish(i, phrase, numb);
}
void finish(int a, char *b, int c)
{
while(b[a]!='\0'){
if(isdigit(b[a])==1){
c++;
}
a++;
}
printf("\nThe phrase you entered has %i numbers",a);
}
从技术上讲,该程序可以工作 - 但它会将输入的所有内容都计算为整数 - 例如,输入 "hello44" 会注册为 6 个数字,而不是只有 2 个。
我制作的一个类似程序在正确注册相同的短语时没有问题,因为只包含 2 个数字,所以我的问题是什么,我该如何在仍然使用函数的同时解决它?
【问题讨论】:
-
另请注意,
isdigit()不需要在成功时返回1,只是它不是0。 -
关于函数:
gets()该函数已经贬值多年,并从(大约)2009 年完全从 C 语言中删除。建议使用fgets()(具有不同的参数列表)跨度> -
关于:
if(isdigit(b[a])==1){这是isdigit()的错误用法。建议:if( isdigit(b[a]) ){ -
关于:
finish(i, phrase, numb);和void finish(int a, char *b, int c)main()`中的变量numb只有在传递numb的地址的情况下才能更新。因此这两个语句应该是:finish(i, phrase, &numb);和void finish(int a, char *b, int *c)。然后在更新值时,而不是c++;使用(*c)++;类似的考虑存在于finish()的第一个参数