C:忽略输入文件中的注释行
im使用fscanf函数处理输入。现在在输入中,必须忽略以#开头的每一行。如何忽略完整的行?例如,此输入:C:忽略输入文件中的注释行,c,input,line,ignore,C,Input,Line,Ignore,im使用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 custo
#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
如您所见,注释的长度可能不同,命令的结构也不同。。。有什么办法区分这两条线吗?或者一种判断我们何时在一行的末尾/开头的方法?使用
fgets()
而不是fscanf()
进行面向行的输入,而不是自由形式的输入。而不是使用fscanf()
,用fgets()
读取行,并使用anfscsc()
替换fscanf()
问题是我们不允许在作业中使用fgets(),因为它会导致内存泄漏和安全问题…@Yanal:huh?您是否在谈论
get()
fgets()
非常容易安全使用(就像我的回答中那样),可以防止内存泄漏或安全问题。不,它不是。你确定你没有把fgets()
和坏掉的gets()
混淆吗?问题是我们不允许在赋值中使用fgets(),因为它会导致内存泄漏和安全问题。。。
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 */
}
}