C编程 "weird output"

标签 c arrays string

我正在尝试创建一个给定字符串的函数,它会像下面所示那样处理该字符串,并修改结构变量的值。用简单的语言来说,给定一个字符串,它会修改变量的坐标。

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/

相关文章:

PHP 对 MySQL 中的数组计数不正确

javascript - 将平面列表转换为父子树

c - 如何更改动态调整大小的数组的指针?

c - 如何 : Cross-Operating-System Large File IO in C?

你能帮我理解这个程序吗?

c++ - makefile中汇编文件的生成

php - 在选择首先替换字符串部分的顺序时替换字符串

c - 查找并替换 C 中所有出现的子字符串

java - 我搜索实现函数获取字符串中出现次数最多的字符并对其进行计数

java - 为什么同一个 interned String 文字在此 java 代码片段中具有多个值?