[英]Removing text after character c
我从输入文件中看到一些看起来像这样的文本:
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'和“”的一些东西,但没有一个完全奏效。
提前致谢!
你可以这样做,但你不需要设置标志。 您可以立即截断该行并停止任何进一步的搜索break;
for(int x = 0; x < 100; x++)
{
if(line[x] == '#') {
line[x] = '\n';
line[x + 1] = '\0';
break;
}
}
在调试器中运行此代码以查看它正在执行的操作。 可能在你的外部while
循环中设置一个断点,并一次单步执行一个字符以准确理解行为。 您可能会明白下一步该做什么。
如果在unix上使用gdb
,请使用-g
编译程序以包含调试信息,并使用google之类的“gdb cheatsheet”开始。
您可以使用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;
}
请参阅此处以供参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.