繁体   English   中英

如何从C ++中的getline函数中提取特定的子字符串?

[英]How to extract specific substring from getline function in C++?

我是C ++的新手,所以如果我的术语或方法不正确,请原谅我。

我正在尝试编写一个简单的程序,该程序:

  1. 打开两个输入文件(“ infileicd”和“ infilesel”)。
  2. 打开一个输出文件“ list.txt”。
  3. 逐行比较“ infilesel”和“ infileicd”。
  4. 如果在“ infileicd”中找到了“ infilesel”中的一行,则会将该行从“ infileicd”写入“ list.txt”,从而有效地创建了单独的日志文件。

我正在使用getline()函数来执行此操作,但是在尝试比较每个文件行时遇到了麻烦。 我认为如果只使用感兴趣的子字符串作为比较会更容易。 问题在于整个getline字符串中有多个单词,而我只对第二个单词真正感兴趣。 这是两个示例:

“ 1529 nic1_mau_op_mode_3” 8664afm007-01“” 1“输出1 0逻辑4 4136”

“ 1523 pilot_mfd_only_sel” 8664afm003-02“” 1“输出1 0逻辑4 4112”

“ nic1_mau_op_mode_3”和“ pilot_mfd_only_sel”是唯一感兴趣的子字符串。

如果我只能使用第二个子字符串进行比较,但是我不知道如何从getline()函数中专门提取它,它将使工作变得容易得多。 我还没有发现任何暗示无法执行此操作的建议,但是如果不可能,那么提取该子字符串的另一种方法是什么?

这是一个个人项目,因此我没有时间限制。

提前非常感谢任何帮助。 这是我的代码(到目前为止):

int main()
{
    //Open the file to write the selected variables to.
    ofstream writer("list.txt");

    //Open the selected variabels file to be read.
    ifstream infilesel;
    infilesel.open("varsel.txt");

    //Open the icd file to be read.
    ifstream infileicd;
    infileicd.open("aic_fdk_host.txt");

    //Check icd file for errors.
    if (infileicd.fail()){
        cerr << "Error opening icd.\n" << endl;
        return 1;
    }
    else {
        cout << "The icd file has been opened.\n";
    }

    //Check selected variables file for errors.
    if (infilesel.fail()){
        cerr << "Error opening selection file.\n" << endl;
        return 1;
    }
    else {
        cout << "The selection file has been opened.\n";
    }

    //Read each infile and copy contents of icd file to the list file.

    string namesel;
    string nameicd;

    while(!infileicd.eof()){ 

        getline(infileicd, nameicd);
        getline(infilesel, namesel);

        if (nameicd != namesel){ //This is where I would like to extract and compare the two specific strings
            infileicd; //Skip to next line if not the same

        } else {
                writer << nameicd << namesel << endl;
        } 
    }


    writer.close();
    infilesel.close();
    infileicd.close();

    return 0;
}

因此,根据我们在评论中讨论的内容,您只需要扔掉不需要的东西。 所以试试这个:

string namesel;
string nameicd;
string junk;

while(!infileicd.eof()){ 

    // Get the first section, which we'll ignore
    getline(infileicd, junk, ' ');
    getline(infilesel, junk, ' ');

    // Get the real data
    getline(infileicd, nameicd, ' ');
    getline(infilesel, namesel, ' ');

    // Get the rest of the line, which we'll ignore
    getline(infileicd, junk);
    getline(infilesel, junk);

基本上, getline采用分隔符,默认情况下为换行符。 通过第一次将其设置为空格,您可以使用相同的方法摆脱第一个垃圾区域,获得所需的零件,然后最后一部分移至该行的末尾,也将其忽略。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM