检查文本文件在C++格式是否正确

Checking if text file is properly formatted in C++

本文关键字:是否 格式 C++ 文本 文件 检查      更新时间:2023-10-16

如何检查文件中的每一行格式是否正确?

例如,假设我有这个文本文件"

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;
        }
    }
}

此代码允许各种形式的分数浮点语法。您可能希望使其更严格或允许指数形式 - 只需修改正则表达式:)