简体   繁体   English

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

[英]How to remove single character from line read from file in C

How can I remove the "@" from "@2" is a .asm file?如何从“@2”中删除“@”是一个 .asm 文件? My output is currently incorrect when read from the file, but when using just "2" it produces the proper binary result.从文件中读取时,我的输出当前不正确,但是当仅使用“2”时,它会产生正确的二进制结果。

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);
}

The Add.asm file is below and from the nand2tetris project. Add.asm 文件位于 nand2tetris 项目下方。

 @2
 D=A
 @3
 D=D+A
 @0
 M=D

Based on your output the @ comes always at the beginning of the strings.根据您的输出, @始终位于字符串的开头。 So you can easily do this:所以你可以很容易地做到这一点:

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

If you want to remove a @ at some random position, then you should write a function like this如果你想在某个随机位置删除@ ,那么你应该写一个这样的函数

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;
}

Then you can call it like然后你可以这样称呼它

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

This would print abcdef这将打印abcdef

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM