用正则表达式验证表格的格式

/*--------------------------------------------------------------
    用正则表达式验证一个表格的格式。
    如果表格格式合乎要求,程序会输出 "all is well" 到 cout;
    否则会将错误消息输出到 cerr。
    一个表格由若干行组成,每行包含四个由制表符分隔的字段。
    例如:
    Class    Boys    Girls    Total 
    1a       12      15       27
    1b       16      14       30
    Total    28      29       57
  --------------------------------------------------------------*/ 
#include <iostream>
#include <fstream> 
#include <regex>
#include <string>
using namespace std;

int main()
{
    ifstream in("table.txt");     //输入文件 
    if(!in) cerr << "no file\n";
    
    string line;                  //输入缓冲区    
    int lineno = 0;
     
    regex header {R"(^[\w]+(\t[\w]+)*$)"};               //制表符间隔的单词
    regex row {R"(^([\w]+)(\t\d+)(\t\d+)(\t\d+)$)"};     //一个标签后接制表符分隔的三个数值 
    
    if(getline(in,line)){         //检查并丢弃标题行
        smatch matches;
        if(!regex_match(line,matches,header))
            cerr << "no header\n";
    } 
    
    int boys = 0;              //数值总计
    int girls = 0;
    while(getline(in,line)){
        ++lineno;
        smatch matches;
        
        if(!regex_match(line,matches,row))
            cerr << "bad line: " << lineno << ‘\n‘;
        
        int curr_boy = stoi(matches[2]);
        int curr_girl = stoi(matches[3]);
        int curr_total = stoi(matches[4]);
        if(curr_boy+curr_girl!=curr_total) 
            cerr << "bad row sum\n";
        
        if(matches[1]=="total"){ //最后一行
            if(curr_boy!=boys) 
                cerr << "boys do not add up\n";
            if(curr_girl!=girls)
                 cerr << "girls do not add up\n";
            cout << "all is well\n";
            return 0; 
        } 
        boys+=curr_boy;
        girls+=curr_girl;
    } 
    
    cerr << "didn‘t find total line\n";
    return 1;     
}

相关推荐