如何从C中的文件行中删除单个字符

时间:2018-03-02 02:29:54

标签: c

如何从“@ 2”中删除“@”是一个.asm文件?从文件中读取时,我的输出当前是错误的,但是当仅使用“2”时,它会产生正确的二进制结果。

<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<div id="demo">

  <input type="text" placeholder="box1" v-focus-if:box1="whichHasFocus"><br>
  <input type="text" placeholder="box2" v-focus-if:box2="whichHasFocus"><br>
  <button @click="changeFocus()">Change Focus</button>

</div>

Add.asm文件位于nand2tetris项目之下。

FILE *fp;
char buffer[256];
fp = fopen("Add.asm", "r");

if(fp == NULL){
    printf("Error opening file\n");
}
else{
    while(fgets(buffer, 256, fp) != NULL){
        buffer[strcspn(buffer, "\r\n")] = 0;
        printf("Buffer:");
        printf("%s\n",buffer);

        if(aOrC(buffer) == true){
            int changer = stringToInt(buffer);
            printf("%s\n",intToBinary(changer));
        } else if(aOrC(buffer) == false){
            char* jump = jumpBits(buffer);
            char* dest = destBits(buffer);
            char* comp = compBits(buffer);
            char* finalBits = finalBinaryC(comp, dest, jump);
            printf("%s\n", finalBits);
        }
    }
    fclose(fp);
}

1 个答案:

答案 0 :(得分:1)

根据您的输出,@始终位于字符串的开头。所以 你可以轻松地做到这一点:

// str contains the string "@2"
puts(str + (str[0] == '@' ? 1 : 0));

如果你想在某个随机位置删除@,那么你应该写一个 像这样的功能

char *remove_char(char *src, char c)
{
    if(src == NULL)
        return NULL;

    char *p = strchr(src, c);

    if(p == NULL)
        return src; // c not found

    // removing c
    memmove(p, p+1, strlen(p));

    return src;
}

然后您可以将其称为

char line[] = "abc@def";
puts(remove_char(line, '@'));

这将打印abcdef