如何解决我在为字符串使用指针时遇到问题
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<string.h>
#include<math.h>
char slova(char a);
int main()
{
char a[100];
fgets(a,sizeof(a),stdin);
char slova(a);
return 0;
}
char slova(char a)
{
int i,x=0,y=0,n;
n=strlen(a);
for(i=0;i<n;i++);
{
if(*(a+i)>='A' && *(a+i)<='Z') x++;
if(*(a+i)>='a' && *(a+i)<='z') y++;
}
if(y>x) return -1;
if(y<x) return 1;
if(x==y || (x==0 && y==0)) return 0;
}
任务是在字符串包含更多小写字母的情况下返回-1,在字符串包含更多大写字母的情况下返回1,并在包含0个字母或相等数目的大小写字母的情况下返回0。我是第一次处理此类任务,并且遇到了很多错误,不确定如何解决。这是错误。
11 14 C:\Users\x\Documents\asgsgg.cpp [Error] invalid conversion from 'char*' to 'char' [-fpermissive]
17 12 C:\Users\x\Documents\asgsgg.cpp [Error] invalid conversion from 'char' to 'const char*' [-fpermissive]
20 11 C:\Users\x\Documents\asgsgg.cpp [Error] invalid type argument of unary '*' (have 'int')
最后一个在第20行出现2次,在第21行出现2次。
解决方法
您需要调用slova()
函数,而不仅仅是声明它,并对结果执行某些操作,例如打印结果。
参数应为char *a
,而不是char a
,因此它是指向字符串的指针,而不是单个字符。
您应该使用功能isupper()
和islower()
而不是自己检查字符范围。
无需检查(x==0 && y==0)
;如果它们都是0
,则x == y
为真。您还可以使用一系列else if
,最后使用else
。
在;
行的末尾有一个额外的for(i=0;i<n;i++)
,因此它后面的代码块不在循环中。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int slova(char *a);
int main(void)
{
char a[100];
fgets(a,sizeof(a),stdin);
printf("Result: %d\n",slova(a));
return 0;
}
int slova(char *a)
{
int i,x=0,y=0,n;
n=strlen(a);
for(i=0;i<n;i++)
{
if(isupper(*(a+i))) x++;
if(islower(*(a+i))) y++;
}
if(y>x) return -1;
else if(y<x) return 1;
else return 0;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。