我在文本文件中給出了一列字符串,我必須將它們相互比較 - 我想比較第一個字符串和下面的所有字符串,然後回到第二個字符串並比較它全部在下面等等。問題是我不知道如何編寫它的代碼比較文件中的字符串
0
A
回答
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)選項結合使用,請搜索所有給定的模式。空文件包含零模式,因此 什麼都不匹配。
相關問題
- 1. 比較文本文件的字符串
- 2. 比較字符串文本
- 3. 將文件名與字符串比較
- 4. linux文件比較字符串unincluded
- 5. 中文或日文字符串比較
- 6. 如何比較輸入的字符串並使用矢量Java比較文本文件中的字符串?
- 7. 字符串/字符比較與python中的按位比較
- 8. 字符串比較
- 9. 比較字符串
- 10. 比較字符串
- 11. 字符串比較
- 12. 字符串比較
- 13. 字符串比較
- 14. 比較字符串
- 15. 比較字符串
- 16. 字符串比較
- 17. 比較字符串
- 18. 字符串比較
- 19. 比較字符串
- 20. 字符串比較
- 21. 字符串比較
- 22. 字符串比較?
- 23. 掃描文件以比較字符串。平均比較
- 24. 從文件輸入字符串並比較輸入字符串
- 25. 比較字符串串聯
- 26. 比較字符串指針?比較字符串C
- 27. 在不同文件夾中比較文件名字符串
- 28. 字符串比較沒有比較
- 29. 比較文本文件中的字符串
- 30. 比較和組合文本文件中的字符串數組
在發佈問題之前,您應該先做一些調查。網上有很多教程,您應該搜索'C++讀取文本文件':http://www.cplusplus.com/doc/tutorial/files/,您應該在一個循環中將字符串與'strcmp'進行比較 – Bhoke
我讀過這些東西 - 一旦我將第一個字符串與所有其他字符串進行比較,我如何回到第二個字符串,如何獲取指針,我應該使用seekp()或seekg(),但是這個幾乎是我卡住的地方 – unfi
你必須先從某件事開始。 **然後來這裏。 –