簡體   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