How to put information from file into an arraya and compare two arrays?

I'm new to c++ and have two files

"line.txt" which contains : abcfurfghthehgiowl
"searchwords.txt" : (6 words in total)

As you can see not all the words will be in both

I want to place the contents of these files into arrays where I will compare the words.
Last edited on
Well first, you're trying to load "searchwords.txt.txt", is that what you intended? If you're unsure if a file is opening correctly, do something like:
1
2
3
4
5
ifstream searchTest("searchwords.txt.txt");
if (!searchTest)
{
    cout << "Error opening file\n";
}


So your line.txt contains one block of characters, while your searchwords.txt contains space-delimited words.

line.txt is easy: Just put all the characters into a string.
1
2
3
ifstream infile("line.txt");
string line;
infile >> line;


You can access the string line as an array if you want, e.g. line[0] will be 'a' in your example.
But what is even more convenient is to use string.find().

For example,
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string line = "acdfowlfgh";
    
    size_t index = line.find("owl");
    if (index != std::string::npos)
    {
        std::cout << "owl found!\n";   
    }
    else
    {
        std::cout << "owl NOT found!\n";
    }
}


For the searchTest, you can get each separated word by doing:
1
2
3
4
5
string word;
while (searchTest >> word)
{
    // incorporate line.find(word) here
}

Last edited on
an array of strings:

string sarr[6];

int i = 0;
while (infile >> sarr[i++]); //a very simple read into array loop. note that the eof() approach has problems (you can google specifics on that -- it can be done but its not what people expect and takes a little more care) and the preferred way is this kind of loop.
note that if you have > 6 lines, the array will go out of bounds and fail. We can worry about that kind of thing later, since this is getting you started and the file is known good with 6 entries. (This is done above, but I added some words is all).

It is unclear if you NEED to read the words into an array or not. You may not technically need to, and be forced to by the assignment's requirements, or you may be not knowing that this is doable without storing the words (see above). If you don't need the array, do not use it.

from there I dunno what you really want: you could be looking for the 6 words in the 1 big long string? Is that the goal?
Last edited on
Topic archived. No new replies allowed.