使用C++根据行中的第一个字符串查找行(仅一个)

Find line (one only) based on first string in line using C++

本文关键字:一个 查找 第一个 C++ 使用 字符串      更新时间:2023-10-16

目标:通过搜索电子邮件地址,在数据文件中找到正确的行进行调整

问题:根据下面的当前代码,当我使用string::find时,我可以找到这一行,但当我搜索rick@fakedomain.tld时,我得到了两个命中,即frederick@rick@行。由于电子邮件地址是第一个字段,我不能包含前导空格(分隔符)来解决这个问题。

示例输入数据文件(称为数据文件):

alan@fakedomain.tld q7gPGAdb0zGKHlQd./ Alan Smith
frederick@fakedomain.tld cyHSYctfJpOq7gPGAd Frederick Smith
david@fakedomain.tld nz0hz1uevogQgNxqQA David Smith
rick@fakedomain.tld 4bExd5J3tU7Pi9o/My Rick Smith
john@fakedomain.tld q7gPGAdb0zGKHlQd./0 John Smith

当前c++代码:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
    // Are there the right number of command line arguments
    if (argc < 2) { // expecting 2, the command and email address
        cout << "test [emailaddress]" << endl;
        return 1;
    }
    if (argc > 2) {
        cout << "test: to many arguments" << endl;
        return 1;
    }
    // put the command line arguments into string variables
    string cmd = argv[0];
    string email = argv[1];
    // display the command line for testing - remove secton for production
    string space = " ";
    string cmdline = cmd + space + email + space + oldPW + space + oldPW;
    cout << cmdline << endl;
    // Open the files
    ifstream filein("datafile"); //File to read from
    if(!filein)
    {
        cout << "Error opening file!" << endl;
        return 1;
    }
    string strLine;
    while(getline(filein, strLine))
    {
        // the test to see if this is the line to work with
        size_t found = strLine.find(email);
        if (found != string::npos) {
            // this is the string so add code here to work with it
            cout << strLine << endl;
        }
    }
    return 0;
}

问题:如何只返回与针头完全匹配的线路?

如果它要求不高,希望得到一个教会我的答案,而不仅仅是一些有效的未注释代码,如果我能得到的只有后者,它会接受后者。

可选:如果有更好的方法来完成您看到的代码的其他部分,请随时在您的回答或评论中提出建议。总是热衷于学习更好的方法。

所需输出

./test rick@fakedomain.tld
alan@fakedomain.tld q7gPGAdb0zGKHlQd./ Alan Smith
 - - no match
frederick@fakedomain.tld cyHSYctfJpOq7gPGAd Frederick Smith    
 - - no match
david@fakedomain.tld nz0hz1uevogQgNxqQA David Smith
 - - no match
rick@fakedomain.tld 4bExd5J3tU7Pi9o/My Rick Smith
 |=|=| MATCH
john@fakedomain.tld q7gPGAdb0zGKHlQd./0 John Smith
 - - no match

我得到的输出

./test rick@fakedomain.tld
alan@fakedomain.tld q7gPGAdb0zGKHlQd./ Alan Smith
 - - no match
frederick@fakedomain.tld cyHSYctfJpOq7gPGAd Frederick Smith    
 |=|=| MATCH
david@fakedomain.tld nz0hz1uevogQgNxqQA David Smith
 - - no match
rick@fakedomain.tld 4bExd5J3tU7Pi9o/My Rick Smith
 |=|=| MATCH
john@fakedomain.tld q7gPGAdb0zGKHlQd./0 John Smith
 - - no match

注意:使用g++ test.c -o test 没有编译错误或警告

如果您想确保找到的电子邮件位于字符串的开头,那么只需检查以确保找到的是零。

if (found == 0)
    cout << strLine << endl;

另一种选择是在文件的行上使用std::string::substr,并与operator == 进行直接比较

if (email == strLine.substr(0, email.size()))
    cout << strLine << endl;
相关文章: