CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3

Thread: loop issues

  1. #1
    Join Date
    May 2008
    Posts
    3

    loop issues

    i want to go threw a list of words and find if there is a string thats equal to another list. But my loop only finds one word of the four that it should. any help would be much appriciated.

    ifstream fin;
    fin.open ( "Wordlist.txt" );
    ifstream fin2;
    fin2.open ( "Words.txt" );
    string line;
    string line2;

    while ( getline ( fin2, line2 ) )
    {
    while ( getline ( fin, line ) )
    {
    if ( line == line2 )
    {
    cout << "Found word that matched: " << line << endl;
    }
    }
    }

  2. #2
    Join Date
    Feb 2003
    Posts
    377

    Re: loop issues

    The problem is that your code is set up to go through the entire Wordlist.txt file for each line in Words.txt. After the first time through, you don't reset the file stream to point to the beginning again. To solve this, you could declare your fin ifstream inside the first while loop, or you could clear() the stream and reposition the file pointer to the beginning.

    However, your algorithm isn't a really good one because it reads the same file over and over. You should consider coming up with another solution. Perhaps by storing the words in the Words.txt file and then going through the Wordlist.txt one line at a time (or vice versa). how you do that depends on how much C++ you know and how much you're allowed to use.

  3. #3
    Join Date
    Oct 2002
    Location
    Timisoara, Romania
    Posts
    14,360

    Re: loop issues

    Quote Originally Posted by DDCO
    i want to go threw a list of words and find if there is a string thats equal to another list. But my loop only finds one word of the four that it should. any help would be much appriciated.

    ifstream fin;
    fin.open ( "Wordlist.txt" );
    ifstream fin2;
    fin2.open ( "Words.txt" );
    string line;
    string line2;

    while ( getline ( fin2, line2 ) )
    {
    while ( getline ( fin, line ) )
    {
    if ( line == line2 )
    {
    cout << "Found word that matched: " << line << endl;
    }
    }
    }
    Can you provide an example? I'm not sure I understand it. Do you want to check whether a line in a file contains all the words in a list?
    Marius Bancila
    Home Page
    My CodeGuru articles

    I do not offer technical support via PM or e-mail. Please use vbBulletin codes.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured