C++ 中的空字段和不存在的字段

empty fields and nonexistent fields in C++

我正在阅读 "Programming Principles and Practice Using C++ 2nd edition",第 23 章中有一个理论问题是关于这样的场

  1. What is the difference between an empty field and a nonexistent field?

我能在书中找到的最好的东西是关于什么是字段的信息。用我的话来说,这是格式化整数值以控制它们在输出中的显示方式的方法。 例如 setw() 操纵器可用于更改数字在输出中的显示方式。

我在 Google 中也找不到任何东西,所以如果有人可以留下一些快速、简短的评论,那将对我有很大帮助。

或者我最好问一下

What is an empty field and what's a nonexistent field?

编辑:我正在阅读的章节称为 "Text manipulation",Bjarne 在这里介绍正则表达式以阅读 table(4 列和很多行)以查看如果 table 中的所有信息都匹配模式

这是来自另一个论坛的答案,是一位好人为我回答的:)

#include <iostream>
#include <string>
#include <regex>

void display_field( const std::string& text, const std::string& name )
{
    // the field that we are interested in is the marked subexpression ([[:alnum:]]*)
    // ie. zero or more alphanumeric characters immediately after 'name='
    const std::regex regex( name + '=' + "([[:alnum:]]*)" ) ;
    std::smatch match_results ;
    std::regex_search( text, match_results, regex ) ;

    std::cout << "'" << name << "' == " ;
    if( match_results.empty() ) std::cout << "  --- (nonexistent field)\n\n" ;
    else if( match_results[1].length() == 0 ) std::cout << "''  --- (empty field)\n\n" ;
    else std::cout << "'" << match_results[1] << "'  --- (non-empty field)\n\n" ;
}

int main()
{
    const std::string text = "name=etrusks email= posts=168 phone= " ;
    for( std::string fn : { "name", "email", "posts", "age", "phone", "address" } )
        display_field( text, fn ) ;
}

这只是一个很好的答案,很高兴:)

输出:

'name' == 'etrusks' --- (non-empty field)
'email' == '' --- (empty field)
'posts' == '168' --- (non-empty field)
'age' == --- (nonexistent field)
'phone' == '' --- (empty field)
'address' == --- (nonexistent field)