C语言 将空格添加回我的汇编程序



到目前为止,我得到了一个汇编程序,用于以 - main: mov %a,0x04 ; sys_write 这样的行开头的作业。有些行包含标签(即末尾带有分号的单词),有些则不包含。;之后的所有内容都是评论,需要删除。空格需要删除并放回原处,以便成品看起来像这样 - main: mov %a,0x04 .我花了很多天的时间,想知道你们是否知道如何放置空格,因为目前它看起来像这样 - main:mov%a,0x04.任何普遍添加空格的可靠方法将不胜感激。

int i;
char line[256];
while(fgets(line,256,infile) != NULL)
{
    char label[256];
    int n = 0;
    for( i=0; i<256; i++)
    {   
        if(line[i] == ';') // checks for comments and removes them
            {   
            label[n]='';
            break;
            }
        else if(line[i] != ' ' && line[i] != 'n') 
            {
            label[n] = line[i]; // label[n] contains everything except whitespaces and coms
            n++;
            }
    }
    char instruction[256];
    for(n =0; n<strlen(label);n++)
    {
        //don't know how to look for commands like mov here
        // would like to make an array that puts the spaces back in?
    }
    // checks if string has characters on it.
    int len = strlen(label);
    if(len ==0)
        continue;
    printf("%sn",label);
}
fclose(infile);
return 0;

我将字符串分成空格之间的子字符串,然后在它们之间添加一个空格。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
FILE *infile=fopen("assembly","r");
char line[256];
while(fgets(line,256,infile) != NULL)
{
    char* tok=strtok(line,";");                     //search for comma
    char* label=malloc(strlen(tok)*sizeof(char));   //allocate memory for 
                                                    //string until comma
    strcpy(label,"");                               //clean string
    tok=strtok(tok," ");                            //search for space
    while(tok != NULL){
        if(strlen(label)>0)                         //when not empty,
            strcat(label," ");                      //add space
        strcat(label,tok);
        tok=strtok(NULL," ");
    }
    printf("%s_n",label);
    free(label);
}
fclose(infile);
return 0;

如果你仍然想以你的方式做,我会这样做

(...)
    else if((line[i] != ' ' && line[i] != 'n')||(line[i-1] != ' ' && line[i] == ' ')) 
        {                   // also copy first space only
        label[n] = line[i]; // label[n] contains everything except whitespaces and coms
        n++;
        }
    }
    printf("%sn",label);
}
fclose(infile);
return 0;
}

最新更新