如何在读取文本文件时跳过白行?
我想逐行读取文本文件,但我对白线不感兴趣。有什么好方法可以跳过空白行?我知道我可以读取一行,检查它是否为空白,如果是空白则释放它,依此类推,直到我到达一行,但我想知道是否还有其他方法可以做到这一点。
I want to read a text file line by line, but I'm not interested in the white lines. What nice way is there of skipping the blank lines? I know I could read a line, check if it's blank and free it if it is, and so on until I reach a good line, but I'm wondering if there's some other way to do it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我觉得你的方法已经足够好了。从技术上讲,您甚至应该检查它是否只是空格 :-) 请注意,如果您使用
fscanf
(在家庭作业问题中经常使用),则白线跳过“包含在价格中”:-) 并且您不这样做不必对抗“这条线比我的缓冲区大,我该怎么办?”I think your method is good enough. Technically you should even check if it's only spaces :-) Note that if you are using
fscanf
(quite used in homework problems), white line skipping is "Included in the price" :-) AND you don't have to fight against "this line is bigger than my buffer, what should I do?"一般概念很好......您逐行阅读并检查它是否具有非空白字符。检查它的一个相当最佳的方法是使用 strspn ...例如:
The general concept is fine ... you read in line by line and check to see if it has a non-whitespace character. A fairly optimum way of checking for it is to use strspn ... for example:
如果逐行读取,请使用简单的“\n”检查(即使您真正的操作系统换行符是 \r\n,编译器也会注意)。
如果使用 fread 读取整个文件,使用 strtok 或 strtok_r 使用 sep='\n' 分割行,空行将自动删除。
If reading line by line use a simple check of '\n' (compiler will take care even if your real OS newline is \r\n).
If using fread to read whole file use strtok or strtok_r to split lines using sep='\n', empty lines will chopped out automatically.