如何使用 C++ 优雅地读取整数溪流?
我有一个充满这种格式行的文件:
1 - 2: 3
我只想使用 C++ 流加载数字。最优雅的方法是什么?我只考虑了 cin.get() 并检查每个字符是否是数字。
I have a file full of lines in this format:
1 - 2: 3
I want to only load numbers using C++ streams. Whats the most elegant way to do it? I only thought about cin.get() and checikng each char if it is number or not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我认为这将是最快但又优雅的方式:
I think this one would be the fastest -yet elegant- way:
您可以使用 区域设置 来更改从文件中读取的内容读。也就是说,您将过滤掉所有非数字值:
然后,当您读取文件时,它会将所有非数字转换为空格,而只留下数字。之后,您可以简单地使用正常转换将正在读取的内容转换为整数。
对以下评论的回应:
这是我为使其发挥作用所做的工作
,这仅将整数放入向量中,仅此而已。它之前不起作用的原因有两个:
You can use a locale to change what things are read from the file as it is being read. That is, you will filter out all non-numeric values:
Then when you read your file, it'll convert all non digits to spaces while leaving you only the numbers. After that, you can simply use your normal conversions to transform what is being read into ints.
Response to the comments below:
Here is what I did to get it to work
And this put only the ints into the vector, nothing more, nothing less. The reason it wasn't working before was two fold:
我建议在阅读本文时至少进行粗略完整性检查:
I would recommend doing at least cursory sanity checks when reading this:
简单地,
Simply,
输入:
输出:
在这里查看自己: http://www.ideone.com/DT9KJ
注意:这可以还要处理额外的空格。所以你甚至可以阅读这个:
类似主题:
使用 ifstream 作为 fscanf
Input:
Output:
See yourself here : http://www.ideone.com/DT9KJ
Note: this can handle extra spaces also. So you can read even this:
Similar topic:
Using ifstream as fscanf
抱歉康拉德,但我建议:永远在死亡的痛苦中,永远永远永远(这足够清楚了吗? :-) 从文件中读取格式化数据。只是不要。
输入格式化数据只有一种正确的方法:读取字符块(通常是行,但也可以读取固定长度的块)。
然后解析输入文本。您不会进行粗略的检查,您将使用一个解析器来保证捕获任何格式错误,并以可理解的方式报告该错误,采取适当的操作(终止、跳过行并继续,等等)。
将输入(I/O 操作)与解析分开。
这个建议来自数十年作为商业程序员的经验:读取格式化输入适用于米老鼠原理证明程序。即使您拥有文件创建的独占控制权,也始终要解析、检查并报告错误:毕竟,内容发生变化,它可能今天有效,但明天就不行了。
我编写 C++ 已有几十年了,但从未读过整数。
Sorry Konrad, but I recommend: never on pain of death, never never never (is that clear enough? :-) read formatted data from a file. Just don't.
There is only one correct way to do input of formatted data: read chunks of characters (typically lines but you can also read fixed length blocks).
Then parse the input text. You're not going to do a cursory check, you going to use a parser that guarantees to catch any formatting error, and report that error in a comprehensible way, take appropriate action (termination, skip the line and continue, whatever).
Separate input (the I/O operation) from parsing.
This advice from decades of experience as a commerical programmer: reading formatted input is for micky mouse proof-of-principal programs. Even if you have exclusive control of the creation of the file, always parse and check and report errors: after all, stuff changes, it may work today but not tomorrow.
I've been writing C++ for decades and I've never read an integer.