【发布时间】:2023-03-27 21:24:01
【问题描述】:
堆栈溢出!我正在学习 C 技术。我有一个函数,它获取一个输入文件,在文件中查找并将内容写入没有 cmets 的输出文件。 该功能有效,但在某些情况下也会刹车。 我的功能:
void removeComments(char* input, char* output)
{
FILE* in = fopen(input,"r");
FILE* out = fopen(ouput,"w");
char c;
while((c = fgetc(in)) != EOF)
{
if(c == '/')
{
c = fgetc(in);
if(c == '/')
{
while((c = fgetc(in)) != '\n');
}
else
{
fputc('/', out);
}
}
else
{
fputc(c,out);
}
}
fclose(in);
fclose(out);
}
但是当我将这样的文件作为输入时:
// Parameters: a, the first integer; b the second integer.
// Returns: the sum.
int add(int a, int b)
{
return a + b; // An inline comment.
}
int sample = sample;
当删除内联注释时,由于某种原因它无法到达“\n”并给出输出:
int add(int a, int b)
{
return a + b; }
int sample = sample;
[编辑] 谢谢你帮助我!它适用于我发布的案例,但它在另一个案例中刹车。 当前代码:
FILE* in = fopen(input,"r");
FILE* out = fopen(output,"w");
if (in == NULL) {
printf("cannot read %s\n", input);
return; /* change signature to return 0 ? */
}
if (out == NULL) {
printf("cannot write in %s\n", output);
return; /* change signature to return 0 ? */
}
int c;
int startline = 1;
while((c = fgetc(in)) != EOF)
{
if(c == '/')
{
c = fgetc(in);
if(c == '/')
{
while((c = fgetc(in)) != '\n')
{
if (c == EOF) {
fclose(in);
fclose(out);
return; /* change signature to return 1 ? */
}
}
if (! startline)
fputc('\n', out);
startline = 1;
}
else if (c == EOF)
break;
else {
fputc('/', out);
startline = 0;
}
}
else
{
fputc(c,out);
startline = (c == '\n');
}
}
fclose(in);
fclose(out);
当文件包含除法时,第二个变量消失。 示例:
int divide(int a, int b)
{
return a/b;
}
它回馈:
int divide(int a, int b)
{
return a/;
}
【问题讨论】:
-
你的代码有几个问题,如果你想看我的回答
-
除了 Bruno 的 cmets,想想如果序列“
//”出现在字符串文字中会发生什么(这里不是注释) -
@DavidC。是的,我也在考虑;-)
-
另外两个讨厌的东西:
// this comment continues \(在换行符之前加上反斜杠)意味着一行注释至少继续到下一行。注释开头的类似结构 — 包含"/\\\n/ This is a comment\n"的字符串,其中第一个和第二个斜杠之间有一个反斜杠换行符序列(或多个 BSNL 序列)也标志着评论的开始。诚然,编写此类代码的程序员应该被枪杀、绞死、画图和四等分,但有些程序需要防弹。您是否担心它的呼吁。 -
@bruno 谢谢。谢谢大家!
标签: c comments c-preprocessor