2016-11-05 90 views
0

我在文本文件中給出了一列字符串,我必須將它們相互比較 - 我想比較第一個字符串和下面的所有字符串,然後回到第二個字符串並比較它全部在下面等等。問題是我不知道如何編寫它的代碼比較文件中的字符串

+0

在發佈問題之前,您應該先做一些調查。網上有很多教程,您應該搜索'C++讀取文本文件':http://www.cplusplus.com/doc/tutorial/files/,您應該在一個循環中將字符串與'strcmp'進行比較 – Bhoke

+0

我讀過這些東西 - 一旦我將第一個字符串與所有其他字符串進行比較,我如何回到第二個字符串,如何獲取指針,我應該使用seekp()或seekg(),但是這個幾乎是我卡住的地方 – unfi

+0

你必須先從某件事開始。 **然後來這裏。 –

回答

1

使用嵌套循環做你期望的;

#include <iostream> 
#include <fstream> 
#include <vector> //include this to use vector 

using namespace std; 

int main() { 

    //to take input from the file 
    ifstream fin; 

    //to read the same strings into 2 arrays so we can loop it appropriately 
    //by taking one string and comparing it to all below it. 
    vector <string> line1; 
    vector <string> line2; 

    //to hold a line of string 
    string temp; 

    //replace this with with your file 
    fin.open("hello.txt"); 

    //to check if file cannot be opened or does not exist 
    if(!fin.is_open()) { 
     cout << "file could not be opened"; 
    } 

    //strings are inserted into element of these 2 vectors 
    //(Internally, vectors use a dynamically allocated array to store their elements in adjacent memory locations) 
    //that is why i decided to use vectors. Also, using the push_back method 
    //to insert the strings into both arrays means we don't have to specify the size of the array 
    while (getline(fin, temp)) { 
     line1.push_back(temp); 
     line2.push_back(temp); 
    } 


    //nested loop is used to make sure one string is used to operate 
    //on all the strings in the file and move to the next to do same 
    //and so on... 
    for (unsigned int i = 0; i < line1.size(); i++) { 
     for (unsigned int j = 0; j < line2.size(); j++) { 
      //you can compare first string with all below here however you want to do it 
      //I just did this so you see how it behaves 
      cout << line1[i] << " = " << line2[j] << endl; 
     } 
    } 

    return 0; 
} 
0

最簡單的方法是使用CMD的Linux像grep的:

// 1路

grep -w -v -f file1.log file.2 > mach.log 

// 2路

grep -w -f file1.log file.2 > mach.log 

你千萬不能忘記旗幟的意思:

-w, --word-regexp 只選擇那些包含構成整個單詞的匹配的行。測試是匹配子字符串必須位於行首,或者以非單詞組成字符開頭。 類似地,它必須位於行尾,或者後面跟着一個非單詞組成字符。單詞組成字符是字母,數字和下劃線。

-v, - 反轉匹配 反轉匹配的意義,選擇不匹配的行。

-f FILE,--file = FILE 從FILE獲取模式,每行一個。如果此選項多次使用或與-e(--regexp)選項結合使用,請搜索所有給定的模式。空文件包含零模式,因此 什麼都不匹配。