<分区>
我在一个文本文件中得到了一列字符串,我必须将它们相互比较 - 我想比较第一个字符串和它下面的所有字符串,然后返回到第二个字符串并将它和它下面的所有字符串进行比较等等。问题是我不知道如何为它编写代码
<分区>
我在一个文本文件中得到了一列字符串,我必须将它们相互比较 - 我想比较第一个字符串和它下面的所有字符串,然后返回到第二个字符串并将它和它下面的所有字符串进行比较等等。问题是我不知道如何为它编写代码
最佳答案
使用嵌套循环可以达到您的预期;
#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;
}
关于c++ - 比较文件中的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40437564/