如何知道fscanf中的换行符?

发布于 2024-07-30 00:45:43 字数 217 浏览 2 评论 0原文

如何知道 fscanf 到达文件中的新行 \n 。 我一直在使用我自己的函数来做到这一点。 我知道我可以使用 fgets 然后使用 sscanf 来获取所需的模式。 但我的要求并不稳定,有时我想要得到制表符分隔的字符串,有时我想要换行分隔的字符串,有时一些特殊字符分隔的字符串。 因此,如果有任何方法可以从 fscanf 了解新行,请帮助我。 或者也欢迎任何替代方式。

提前致谢。

How to know that fscanf reached a new line \n in a file.
I have been using my own functions for doing that. I know I can use fgets and then sscanf for my required pattern. But my requirements are not stable, some times I want to get TAB separated strings, some times new line separated strings and some times some special character separated strings. So if there is any way to know of new line from fscanf please help me. Or else any alternative ways are also welcome.

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青衫儰鉨ミ守葔 2024-08-06 00:45:46

Kernighan 和 Pike 在优秀著作“编程实践”中展示了如何使用 sprintf() 创建适当的格式说明符,包括长度(类似于 AProgrammer 答案中的示例),然后在对 scanf() 的调用中使用它>。 这样,您还可以控制分隔符。 对这种方法“效率低下”的担忧可能是错误的——替代方案更难找到正确的选择。

也就是说,我通常不会使用 scanf() 系列函数进行文件 I/O; 我使用某种“获取行”例程将数据获取到字符串中,然后使用 sscanf() 函数系列将其拆分 - 或其他更专业的解析代码。

Kernighan and Pike in the excellent book 'The Practice of Programming' show how to use sprintf() to create an appropriate format specifier including the length (similar to the examples in the answer by AProgrammer), and then use that in the call to scanf(). That way, you can also control the separators. Concerns about the 'inefficiency' of this approach are probably misguided - the alternatives are harder to get right.

That said, I most normally do not use the scanf() family of functions for file I/O; I get the data into a string with some sort of 'get line' routine, and then use the sscanf() family of functions to split it up - or other more specialized parsing code.

妞丶爷亲个 2024-08-06 00:45:45
fscanf(stream, "%42[^\n]", buffer);

与 fgets(buffer, 42, stream) 等效。 您不能将 42 替换为 * 来指定参数中的缓冲区长度(就像在 printf 中所做的那样),其含义是抑制赋值。 因此,

fscanf(stream, "%*[^\n]%*c");

请阅读(并包含)下一个行尾字符。

除 [、c 和 n 之外的任何转换说明符都以跳过空格开头。

fscanf(stream, "%42[^\n]", buffer);

is an equivalant of fgets(buffer, 42, stream). You can't replace the 42 by * to specify the buffer length in the argument (as you can do in printf), its meaning is to suppress the assignment. So

fscanf(stream, "%*[^\n]%*c");

read upto (and included) the next end of line character.

Any conversion specifier other than [, c and n start by skipping whitespaces.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文