C: 忽略输入文件中的注释行

tim*_*sa7 4 c input line

我使用 fscanf 函数来处理输入。现在在输入中以# 开头的每一行都必须被忽略。我如何忽略完整的一行?例如这个输入:

#add some cars
car add 123456 White_Mazda_3 99 0
car add 123457 Green_Mazda_3 101 0
car add 111222 Red_Audi_TT 55 1200

#let see the cars
report available_cars

#John Doe takes a white mazda
customer new 123 JohnDoe
customer rent 123 123456

#Can anyone else take the mazda?
report available_cars

#let see Johns status
report customer 123
Run Code Online (Sandbox Code Playgroud)

如您所见,注释的长度可能有所不同,命令的结构也有所不同……有什么方法可以区分两行吗?或者一种告诉我们何时在一行的末尾/开头的方法?

pmg*_*pmg 5

而不是 using fscanf(),读取行fgets()并使用sscanf()来替换fscanf().

char s1[13], s2[4], s3[17], s4[43];
char line[1000];
while (fgets(line, sizeof line, stdin)) {
    if (*line == '#') continue; /* ignore comment line */
    if (sscanf(line, "%12s%3s%16s%42s", s1, s2, s3, s4) != 4) {
        /* handle error */
    } else {
        /* handle variables */
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 不,它没有。你确定你没有把 `fgets()` 和损坏的 `gets()` 混淆吗? (2认同)