我正在尝试创建一个给定字符串的函数,它会像下面所示那样处理该字符串,并修改结构变量的值。用简单的语言来说,给定一个字符串,它会修改变量的坐标。
typedef struct coo {
int x;
int y;
} Coord;
typedef struct exer{
char ray[1000];
Coord coords[1000];
} exercise;
exercise test;
int coordinates(char *sent){
int i=0,j=1;
test.coords[0].x=0;
test.coords[0].y=0;
if(strlen(test.ray)>=strlen(sent)){
for(;((int) strlen (test.ray) >= j && sent[i]!='\0');i++){
if(sent[i]=='F'){test.coords[j].x = test.coords[j-1].x+1;
test.coords[j].y = test.coords[j-1].y;} else{
if(sent[i]=='L'){test.coords[j].y = test.coords[j-1].y+1;
test.coords[j].x = test.coords[j-1].x;} else{
if(sent[i]=='R'){test.coords[j].y = test.coords[j-1].y-1;
test.coords[j].x = test.coords[j-1].x;} else{
return erromsg(SENT);}
}
}
j++;
}
for(;(int) strlen (test.ray) > i && sent[i]=='\0';){
for(;j<(int) strlen(test.ray);j++){
test.coords[j].x = test.coords[j-1].x+1;
test.coords[j].y = test.coords[j-1].y;
}
}
}
else return errormsg(SENT);
return 1;
}
问题是,当我稍后调用一个函数在屏幕上显示输出时,它会为我提供带有如下字符的坐标: �
以及其他甚至不会复制到此页面的字符: )
我是 C 新手,所以欢迎任何建议。
编辑:打印坐标的代码
int showcoords(){
int k=0;
if(test.coords==NULL) return errormsg(COLOC); else{
while((int) strlen (test.ray)>k){
printf("(%c,%c) ",test.coords[k].x,test.coords[k].y);
k++;
}
}
printf("\n");
return 1;
}
最佳答案
printf
的 %c
说明符表示打印相应的字符,因此 100
-> d
等.由于您的数字与 ASCII/Unicode 无关,因此您会得到看似随机的字符。
只需将 %c
更改为 %d
,即可打印整数。还有许多其他标志,例如用于浮点型和 double 型的 %f
。您还可以应用格式,例如前导零等。
请参阅这个方便的引用:http://www.cplusplus.com/reference/cstdio/fprintf/
关于C编程 "weird output",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15588651/