做题时遇到的坑,归结到一段代码里,作为其中一种方法参考:
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
struct fruit{
char s[100];
double count;
double price;
}a[100];
char * translation(char a)
{
char *s;
s=(char *)malloc(20);
if(a=='a'){
strcpy(s,"apple");
}
else if(a=='o'){
strcpy(s,"orange");
}
else if(a=='b'){
strcpy(s,"banana");
}
else if(a=='p'){
strcpy(s,"pineapple");
}
return s;
}
int main()
{
int i,j,k,m;
double weight;
char huopin;
while(scanf("%d",&m)!=EOF)
{
getchar();
for(i=0;i<m;i++)
{
//getchar();或只放在这一处就够了,写成里外两个是为了易懂哈
scanf("%c",&huopin);
scanf("%lf",&weight);
getchar();
strcpy(a[i].s,translation(huopin));
a[i].count=weight;
}
for(i=0;i<m;i++)
{
printf("%s ",a[i].s);
printf("%.2f\n",a[i].count);
}
}
return 0;
}
运行结果:
总结:
C中,字符串赋值方法可以有:
1、char a[5]=“hello”;
2、char a[5]; strcpy( a, “hello”);
(别忘了加头文件 #include <stdlib.h>)
3、函数返回字符串,上面提供了一种方法,个人觉得比较实用,c和c++通用;
4、用getchar()吸收回车键,解决编程时可能会遇到的坑。
代码如下:
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char a[10] = "hello";
char b[10];
char c[10] = {'h','e','l','l','o'};
/**错误方法
char c[10];
c[10] = "hello";
c = "hello";
*/
strcpy(b,"hello");
printf("a=%s,alength=%d\n",a,strlen(a));
printf("b=%s,blength=%d\n",b,strlen(b));
printf("c=%s,clength=%d\n",c,strlen(c));
return 0;
}