c++ - 比较文件中的字符串

标签 c++ string file compare

<分区>

我在一个文本文件中得到了一列字符串,我必须将它们相互比较 - 我想比较第一个字符串和它下面的所有字符串,然后返回到第二个字符串并将它和它下面的所有字符串进行比较等等。问题是我不知道如何为它编写代码

最佳答案

使用嵌套循环可以达到您的预期;

#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/

相关文章:

c++ - 是否可以计算任意 std::regex 对象中捕获组的数量?

C++ 静态结构类型成员初始化

c# - 字符串中的最后一个和第一个单词c#

java - 如何在输入特定字符串后停止java中的while循环?

.net - 在 VB.NET 中保存数千个文件的最快方法?

c++ - 在另一个构造函数中调用构造函数(没有要调用的匹配函数......)c++

c++ - 从进程导航到它的父进程

java - 使用正则表达式在字符串中查找多个匹配项的索引的问题

c++ - 为什么使用无符号字符写入二进制文件?为什么不应该使用流运算符来写入二进制文件?

python - 通过 Python 创建文件和目录