Hello,

I'm trying to read in words from a text file that look like:
The
World
Fell
Over

etc..

But it doesn't seem to be working.. I've written some code however it will only show the first word OR loads of question marks..

string dictionary()
{
    string words[500];
    ifstream openDictionary (dictLoc.c_str());
    
    if(openDictionary.is_open())
    {
        for(int i=0; (i < !openDictionary.eof()); i++)
        {
            openDictionary >> words[i];  
        }

  }else{
        
        cout << "Cannot open the file";
    }    
    return *words;
}

(Function for reading file / storing words)

string lines = dictionary();
    
    for(int i=0; (i < 500); i++)
    {
        cout << lines[i];
    }

(Code for displaying the different words)

Anyone have any ideas? Thanks

Recommended Answers

All 4 Replies

Try something like this:

#include <fstream>
#include <iostream>
using namespace std;

int main(void)
{
	ifstream fileIn("c:/science/TomDigs.txt");
	char strData[128] = {0};
	string words[500];

	int intCount = 0;
	while(!fileIn.eof() && intCount < 500)
	{
		fileIn >> strData;
		words[intCount++] = strData;
	}

	fileIn.close();
	return 0;
}

But I have to ask: What is it you're actually trying to do?
Have you considered a list or vector?

Basically, create a list of words which I can then check against a string..

e.g. The man sat down
DICTIONARY
The
man

string contains 2 words from dictionary..

And thanks for replying :)

I had some STL-based fun try this task myself, so I thought I'd share it with you :)

#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>

typedef std::istream_iterator< std::string > word_reader;
typedef std::ostream_iterator< std::string > word_writer;

int main()
{
    std::ifstream infile( "MyDictionaryFile.txt", std::ios::in );
    if ( ! infile.is_open() )
        return 1;

    // Create a place to store the dictionary
    std::vector< std::string > dictionary;

    // Read words from file and put them in the dictionary
    std::copy( word_reader( infile ), word_reader(), std::back_inserter(dictionary) );

    // Sort the dictionary
    std::sort( dictionary.begin(), dictionary.end() );

    // Remove duplicate words from the dictionary
    dictionary.erase( std::unique( dictionary.begin(), dictionary.end() ), dictionary.end() );

    // Make a test sentence
    std::string testWords[] = { "the", "dogs", "and", "monkey", "dogs" }    ;

    // sort the words in the test sentence
    std::sort( testWords, testWords + 5 );

    // Find the common words from the test sentence that are in the dictionary
    std::vector< std::string > commonWords;
    std::set_intersection( testWords, testWords + 5, dictionary.begin(), dictionary.end(), std::back_inserter(commonWords) );

    // Print results!
    std::cout << "Found " << commonWords.size() << " words in the dictionary:" << std::endl;
    std::copy( commonWords.begin(), commonWords.end(), word_writer(std::cout, "\n" ) );

    return 0;
}

I'm not sure if it will be of any use to you, but I just wanted to try and do the whole task only using STL containers, iterators and algorithms. I don't know if it's any more or less readable than coding it in a more C-like way, but I do think it has a more aesthetically pleasing feel to it. Personally :)

Anyway, have fun!

Disclaimer: I'm not expecting you to use this; I just wanted to do it.

So, here is a technique for doing the same thing with Linq in C++.
A lot of the work is done for you, but in C++, LINQ is pretty obfuscated:

// DW_396104.cpp : main project file.

#include "stdafx.h"

using namespace System;
using namespace System::Collections::Generic;
using namespace System::IO;
using namespace System::Linq;

List<String^>^ ParseToLowerStringList(String^ str, String^ strSeps)
{ //calling Trim() is obsolete if a space is included in the strSeps
   return
      Enumerable::ToList<String^>(
         Enumerable::Select<String^>(
            Enumerable::Select<String^>(
               str->Split(strSeps->ToCharArray(),
                  StringSplitOptions::RemoveEmptyEntries),
               gcnew Func<String^,String^>(&String::ToLower)),
            gcnew Func<String^,String^>(&String::Trim))
            );
}

int main(array<System::String ^> ^args)
{
   String^ strTargetWords = "The man sat down";
    
   ///////////////////////////////////////////////////
   // create a list of the words from the dictionary.
   List<String^>^ lst_strDictionary = gcnew List<String^>();
   StreamReader^ fileIn = gcnew StreamReader("c:/science/DaniWeb/DW_396104/Dictionary.txt");
   ////////////////////////////////
   // Read, parse, compare, Display
   (gcnew List<String^>(Enumerable::Intersect(
      ParseToLowerStringList(fileIn->ReadToEnd(),"\r\n\t "),
      ParseToLowerStringList(strTargetWords, "\t "))))
      ->ForEach(gcnew Action<String^>(Console::WriteLine));
   fileIn->Close();
    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.