检查文本文件在C++格式是否正确
Checking if text file is properly formatted in C++
如何检查文件中的每一行格式是否正确?
例如,假设我有这个文本文件"
WordOne 0.2
WordTwo 0.1
WordThree 0.38
WordFour WordFour <--- This would be incorrectly formatted.
第一个单词应该是字符串,第二个单词应该是双精度。我怎样才能正确检查这一点?
如果s
是文件关联的文本流,给定std::string wd; double d;
像 s >> wd >> d
这样的表达式将尝试读取单词和双精度,如果它以某种方式失败,则计算为"false"(实际上是 nullPTR)。
此时,您应该重置错误标志 ( s.clear()
),丢弃任何内容以""并继续。( s.ignore(std::numeric_limits<std::streamsize>::max(),'n');
)
您可以计算读取行,就像保存导致读取失败的行号一样。
我认为正则表达式是解决您问题的最佳解决方案。
它们受 C++11 支持:
#include <regex>
#include <string>
#include <vector>
#include <iostream>
auto lines = std::vector<std::string> {
"WordOne 2",
"WordTwo 10.1",
"WordThree 0.38",
"WordThree 0.",
"WordFive WordFive"
};
int main() {
std::regex re("\w+\s+\d+\.?\d*");
for(auto line : lines) {
if(!std::regex_match(line, re)) {
std::cout << "Line: "" << line
<< "" is incorrectly formatted" << std::endl;
}
}
}
此代码允许各种形式的分数浮点语法。您可能希望使其更严格或允许指数形式 - 只需修改正则表达式:)
相关文章:
- 是否可以从格式字符串中检索"width"
- GCC 编译器是否应该对涉及 [[fallthrough]] 属性的格式错误的C++代码进行诊断?
- 如何检查字符串格式在读取C++文本文件时是否有效?
- 如何检查日期格式(日/月/年)是否正确C++
- Visual Studio 是否正式支持 __int64 的 "%lld" 格式说明符?
- 尝试访问类的私有成员以消除重载是否格式不正确
- 在全局命名空间中重载不依赖于用户定义类型的标准定义类型的运算符是否格式正确?
- 检查leandit输入是否具有正确的格式QT 5 C
- 是否可以在 ns2 中以无线跟踪格式添加字段
- OpenGL:是否可能具有16位内部格式,类似于亮度 alpha
- 是否允许复制/移动省略使使用已删除函数的程序格式正确?
- 是否有预定义的内置函数将数字转换为C++二进制格式
- clang格式的对齐分配是否损坏
- 检查文本文件在C++格式是否正确
- 默认参数之后的可变参数格式是否正确
- 是否有适用于 sigma.js兼容 json 文件的专用格式
- 如何检查 XML 是否与 Xerces 格式正确
- 是否有适用于 OpenSceneGraph osg ive 格式的 GDAL 驱动程序
- c++ 14中语句(void)f()的状态是否格式错误?如果不是,f()部分是否为丢弃值
- 检查收到的XML是否格式良好