删除字符c后的文本

时间:2013-04-17 20:03:04

标签: c text input output stdio

我从输入文件中得到一些看起来像这样的文字:

func:
    sll  $t3, $t4, 5       # t1 = (i * 4)
    add  $t3, $a1, $t4     # t2 contains address of array[i]
    sw   $t1, 4($t2)       # array[i] = i
    addi $t2, $t5, 3       # i = i+1

我想“清理”它,并将其输出到另一个文件,如下所示:

func:
    sll  $t3, $t4, 5
    add  $t3, $a1, $t4
    sw   $t1, 4($t2)
    addi $t2, $t5, 3

以下是我用来执行此操作的代码块:

    while(fgets(line, 100, input) != NULL)
   {
    int comment = 0;
    for(int x = 0; x < 100; x++)
    {
        if(line[x] == '#')
            comment = 1;

        if(comment == 1)
            line[x] = '\0'; //I know this is incorrect
    }
    fprintf(cleaned, "%s", line);
   }

如何更改该代码块以便按我的意愿工作?我搞砸了,用'\ n''\ 0'和“”尝试了一些东西,但没有一个完全奏效。

提前致谢!

3 个答案:

答案 0 :(得分:5)

你可以这样做,但你不需要设置旗帜。您可以立即截断该行,并使用break;

停止进一步搜索
for(int x = 0; x < 100; x++)
{
    if(line[x] == '#') {
        line[x] = '\n';
        line[x + 1] = '\0';
        break;
    }
}

答案 1 :(得分:2)

在调试器中运行此代码,以确切了解它在做什么。可能在您的外部while循环中设置一个断点,并一次单步执行一个字符以准确理解该行为。您可能会明白下一步该做什么。

如果在unix上使用gdb,请使用-g编译您的程序以包含调试信息,并启动类似“gdb cheatsheet”的内容。

答案 2 :(得分:0)

您可以使用strchr在您的行中找到“#”。如果找到,则返回指针,如果不是NULL 您可以确定开始和发生之间的差异并创建一个新字符串。

/* strchr example */
#include <stdio.h>
#include <string.h>

int main ()
{
    char str[] = "This is a sample string";
    char * pch;
    printf ("Looking for the 's' character in \"%s\"...\n",str);
    pch=strchr(str,'s');
    while (pch!=NULL)
      {
        printf ("found at %d\n",pch-str+1);
        pch=strchr(pch+1,'s');
      }
    return 0;
}

请参阅here以获取参考。