Hey everybody,

I'm a little stuck on this simple program I'm trying to run. Right now it takes in a list of words and makes a single string out of them, but what I really want to do is make each word into its own new string, or maybe create an array of strings. The goal is to be able to find how how many copies of each word from the file there are, so I need to be able to compare each word with every other word individually.

How might I read each word into its own string?

#include<iostream>
#include<fstream>

using namespace std;

int main(int argc, char * argv[])
{
  char buf[16];

  ifstream fin;

  if (argc < 2)
  {
     cout << "Usage: " << argv[0] << "<filename>\n";
     return -1;
  }

  char * filename = argv[1];

  cout << "File to open: " << filename << endl;

  fin.open(filename);
  if(fin.fail())
  {
     cout << "Failed to open file " << filename << endl;
     return -1;
  }

  string str;

  while (fin >> buf)
  {
      str.append(buf);
      str.append(" ");
  }

  cout << str << endl;

  fin.close();

  return 0;
}

Thanks in advance!

Recommended Answers

All 4 Replies

You could use a vector for this. A vector is a sort of array that can change it's size on the fly. This is very useful when you don't know how much data you want to store.

I've made you a small demo. Just compile and run it, you'll get the basic idea!

#include <iostream>
#include <vector>
#include <string>

using namespace std;

void show (vector<string> *inVec)
{
    cout << "\nNumber of strings in vector: " << inVec->size();
    cout << "\nStrings in vector:\n";
    for (int i = 0; i < inVec->size(); i++) 
        cout << inVec->at(i) << "\n";
}
int main()
{
    vector<string> SomeWords;
    SomeWords.push_back("One");
    SomeWords.push_back("Two");
    show(&SomeWords);
    SomeWords.push_back("Three");
    SomeWords.push_back("Four");
    show(&SomeWords);
    cin.get();
    return 0;
}

Cool, thanks, it looks like vectors are the way to go. But how would I get the words from the file read into different elements of the vector? It seems like I wouldn't be able to just say someWords.push_back(buf) since the string needs to be in quotes, or would I? Is there a way to define what I want to "push_back" that would take input being read from a file?

It seems like I wouldn't be able to just say someWords.push_back(buf) since the string needs to be in quotes, or would I?

It's your lucky day! If 'buf' is of the type 'string', you can just say someWords.push_back(buf) :)

Is there a way to define what I want to "push_back"

Sure. You can say vector<float> for floats, vector<int> for ints, or you could even make a vector of a datatype you made yourself.

Sweet! Thanks, niek_e, your help is much appreciated.

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.