我在文本文件中给出了一列字符串,我必须将它们相互比较 - 我想比较第一个字符串和下面的所有字符串,然后回到第二个字符串并比较它全部在下面等等。问题是我不知道如何编写它的代码比较文件中的字符串
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. 将文件名与字符串比较
- 5. linux文件比较字符串unincluded
- 6. 中文或日文字符串比较
- 7. 比较文本框中的字符串
- 8. 字符/字符串比较
- 9. 字符串字符比较
- 10. 字符串,C++中的字符比较
- 11. 如何比较输入的字符串并使用矢量Java比较文本文件中的字符串?
- 12. 字符串/字符比较与python中的按位比较
- 13. 扫描文件以比较字符串。平均比较
- 14. 比较字符串
- 15. 比较字符串
- 16. 比较字符串
- 17. 字符串比较
- 18. 比较字符串
- 19. 字符串比较
- 20. 字符串比较
- 21. 字符串比较?
- 22. 字符串比较
- 23. 字符串比较
- 24. 字符串比较
- 25. 比较字符串
- 26. 比较字符串
- 27. 字符串比较
- 28. 字符串比较
- 29. 字符串比较
- 30. 字符串比较
在发布问题之前,您应该先做一些调查。网上有很多教程,您应该搜索'C++读取文本文件':http://www.cplusplus.com/doc/tutorial/files/,您应该在一个循环中将字符串与'strcmp'进行比较 – Bhoke
我读过这些东西 - 一旦我将第一个字符串与所有其他字符串进行比较,我如何回到第二个字符串,如何获取指针,我应该使用seekp()或seekg(),但是这个几乎是我卡住的地方 – unfi
你必须先从某件事开始。 **然后来这里。 –