My output looks like this "T h i s m y o u t p u t" and I want it to look like this "This is my output". Any suggestions? I guess what Im asking is how do you take words from a file and put it into an array?

#include <iostream>
#include <fstream>

using namespace std;


int main()
{
   char fileName[80];
   char a[30];
   int names = 0;
   ifstream myfile;
   
   cout << "Enter file name: ";// Get filename from user
   cin >> fileName;

   
   myfile.open(fileName);

   
   while(myfile.good() == false)// Prompt for new file name if not able to open
   {
      cout << "Unable to open file. Enter a different name: ";
      cin >> fileName;
      myfile.open(fileName);
   }

   while (myfile>>a[names]) 
   {  
	   cout<<a[names]<<" ";
   } 
   myfile.close();
   return 0;
}

Recommended Answers

All 17 Replies

this is a c++ program, so use c++ classes

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

using namespace std;

int main()
{
    vector<string> arry;
    ifstream in("filename.txt");
    string word;
    while( in >>  word )
    {
            array.push_back(word);
   }
}

But, in your example while (myfile>>a[names]) should be while (myfile>>a)

while(myfile.good() == false)// Prompt for new file name if not able to open
   {
      cout << "Unable to open file. Enter a different name: ";
      cin >> fileName;
      myfile.open(fileName);
   }

You need to clear the error flags before trying to open the file again when you are in this loop. Otherwise you'll be stuck in an infinite loop even when you enter a good filename.

So say I have a file that has two lines in it, like so:

This is one line
This is another

How would I store line one into one array...like array1={This, is, one, line}
and then line two into array2={This, is, another}?

So say I have a file that has two lines in it, like so:

This is one line
This is another

How would I store line one into one array...like array1={This, is, one, line}
and then line two into array2={This, is, another}?

I would use the getline() function.

Loop untill you hit the end of the file, read in line at a time with getline, then do with it what you want.

While (!(fileStream.eof())) {
cin.getline(array_var, 256, '\n')
}

That doesn't do what you are asking, but it should get you on the right track.

As kylcrow mentioned, getline can come in handy here, but it won't do the whole job. You can use getline to get the lines, then pass the line to another function that splits the line into words. Since you don't know how many words in a line there are ahead of time, you need to declare array sizes larger than the maximum number of words there could be in a line, or use dynamic arrays, or use a vector as Ancient Dragon suggested. But you are for sure going to have to redefine your array if you decide to stick with arrays. You need either a two-dimensional array of char or an array of strings, but a one dimensional array of char isn't what you want here.

Ok so I got the two lines and now I am trying to pass them to the function SplitLines, but im not sure how vectors work, do my char arrays have to be strings? I get an error in the function call.

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

using namespace std;

//prototype of split function
void SplitLines (char a, char b);


int main()
{
   char fileName[80];
   char a[256];
   char b[256];
   int names = 0;
   ifstream myfile;
   
   cout << "Enter file name: ";// Get filename from user
   cin >> fileName;

   
   myfile.open(fileName);

   
   while(myfile.good() == false)// Prompt for new file name if not able to open
   {
      cout << "Unable to open file. Enter a different name: ";
      cin >> fileName;
      myfile.open(fileName);
	   myfile.clear();
   }

   while (myfile) 
   {  
	   myfile.getline(a, 256, '\n');
	   myfile.getline(b, 256, '\n');
	   cout<<a<<" "<<endl;
	   cout<<b<<" ";
	   //function call to split lines into words
	   SplitLines(a, b);
   } 
   myfile.close();
   return 0;
}
//name of fucntion for splitting
void SplitLines (char a[], char b[])
{
	vector<string> array;
	array.push_back(a);
}

Ok so I got the two lines and now I am trying to pass them to the function SplitLines, but im not sure how vectors work, do my char arrays have to be strings? I get an error in the function call.

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

using namespace std;

//prototype of split function
void SplitLines (char a, char b);


int main()
{
   char fileName[80];
   char a[256];
   char b[256];
   int names = 0;
   ifstream myfile;
   
   cout << "Enter file name: ";// Get filename from user
   cin >> fileName;

   
   myfile.open(fileName);

   
   while(myfile.good() == false)// Prompt for new file name if not able to open
   {
      cout << "Unable to open file. Enter a different name: ";
      cin >> fileName;
      myfile.open(fileName);
	   myfile.clear();
   }

   while (myfile) 
   {  
	   myfile.getline(a, 256, '\n');
	   myfile.getline(b, 256, '\n');
	   cout<<a<<" "<<endl;
	   cout<<b<<" ";
	   //function call to split lines into words
	   SplitLines(a, b);
   } 
   myfile.close();
   return 0;
}
//name of fucntion for splitting
void SplitLines (char a[], char b[])
{
	vector<string> array;
	array.push_back(a);
}

Try entering two bad filenames in a row and make sure that you are correctly making sure that the file exists. Also try entering a bad filename, then a good one.

SplitLines should probably take a single line as an argument, not both lines.

Yes, I would get rid of the char array and make everything a string. You can't push a char array onto a vector of string. Also, look at your SplitLines function declaration at the top and then at the actual function. They need to match.

Think about exactly what you are storing in your vector. Is it a vector of entire lines or a vector of words? SplitLines should take a single string for an argument and return a vector of strings. The way you have it now, array is a local variable and nothing is returned, so any work done in the SplitLines function is lost.

I fixed a bunch of the things you mentioned but I guess I just dont know what vector really does. Does push_back separate the line into words? Do i need to take "myfile" to the SplitLines function?

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

using namespace std;

//prototype of split function
void SplitLines (ifstream& myfile, string& a);


int main()
{
   string fileName;
   string a;
   string b;
   int names = 0;
   ifstream myfile;
   
   cout << "Enter file name: ";// Get filename from user
   cin >> fileName;

   
   myfile.open(fileName.c_str());

   
   while(myfile.good() == false)// Prompt for new file name if not able to open
   {
      cout << "Unable to open file. Enter a different name: ";
	  myfile.clear();
      cin >> fileName;
      myfile.open(fileName.c_str());
	  
   }

   while (myfile) 
   {  
	   getline(myfile,a, '\n');
	   getline(myfile,b, '\n');
	   cout<<a<<" "<<endl;
	   cout<<b<<" ";
	   //function call to split lines into words
	   SplitLines(myfile, a);
   } 
   myfile.close();
   return 0;
}
//name of fucntion for splitting
void SplitLines (ifstream& myfile, string& a)
{
	vector<string> array;
	
	while( myfile >>  a )
    {
      array.push_back(a);
    }
	
	
	cout<<endl;
	cout<<a<<endl;
	
}

I fixed a bunch of the things you mentioned but I guess I just dont know what vector really does. Does push_back separate the line into words? Do i need to take "myfile" to the SplitLines function?

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

using namespace std;

//prototype of split function
void SplitLines (ifstream& myfile, string& a);


int main()
{
   string fileName;
   string a;
   string b;
   int names = 0;
   ifstream myfile;
   
   cout << "Enter file name: ";// Get filename from user
   cin >> fileName;

   
   myfile.open(fileName.c_str());

   
   while(myfile.good() == false)// Prompt for new file name if not able to open
   {
      cout << "Unable to open file. Enter a different name: ";
	  myfile.clear();
      cin >> fileName;
      myfile.open(fileName.c_str());
	  
   }

   while (myfile) 
   {  
	   getline(myfile,a, '\n');
	   getline(myfile,b, '\n');
	   cout<<a<<" "<<endl;
	   cout<<b<<" ";
	   //function call to split lines into words
	   SplitLines(myfile, a);
   } 
   myfile.close();
   return 0;
}
//name of fucntion for splitting
void SplitLines (ifstream& myfile, string& a)
{
	vector<string> array;
	
	while( myfile >>  a )
    {
      array.push_back(a);
    }
	
	
	cout<<endl;
	cout<<a<<endl;
	
}

push_back does NOT separate the line into words. That's a separate problem. There's more than one way of doing that and I don't know whether this is for a school assignment or not, or what you've been exposed to. As far as splitting the string into words, you may use the find and substr functions from the string library.

http://www.cplusplus.com/reference/string/string/

Take a look at the functions from cctype too. They could be very useful.

http://www.cplusplus.com/reference/clibrary/cctype/

Once you have the word, which will be stored in a string, then you'll use push_back. There is no need to pass the ifstream at all since you aren't reading from the file in the function. Your function needs to take a string as a parameter. You have a choice. You can either have the function be a void function and pass the vector of strings to it by reference as a second parameter, or you can have the function RETURN a vector of strings and just take the single string as a parameter.

push_back does NOT separate the line into words. That's a separate problem. There's more than one way of doing that and I don't know whether this is for a school assignment or not, or what you've been exposed to. As far as splitting the string into words, you may use the find and substr functions from the string library.

http://www.cplusplus.com/reference/string/string/

Take a look at the functions from cctype too. They could be very useful.

http://www.cplusplus.com/reference/clibrary/cctype/

Oddly enough I was working away at a tokenizer. I think that my snippet might be helpful, but maybe not if this is an assignment.

If it is an assignment, and you absolutely feel the need to split the line of characters (the string) into separate words, refer to this C-style method here

commented: Haven't tried your snippet yet, but will. strtok is a good link. +7

I want to split these two different lines up into words so then I can compare them. To see which is in one and not in the other. Should I be splitting them up and putting them into vectors or arrays? I dont think if if just split them into tokens that will work, or will it?

I want to split these two different lines up into words so then I can compare them. To see which is in one and not in the other. Should I be splitting them up and putting them into vectors or arrays? I dont think if if just split them into tokens that will work, or will it?

Split the lines up into words and place the words for a corresponding line into a vector.

For example, vector<string> a has elements "I", "believe", "in", "you" and vector<string> b has elements "You", "believe", "in", "you".

If you use a == b it will return false because the first element in a isn't equal to the first element in b.

The way the values are compared are defined in the vector's equal operator which is explained here
and more thoroughly explained in this link.

Edit: I do not know if the vector class handles the exception between unequally lengthed vectors, but in the event that you obtain a set of words that are more or less than the vector to be compared against, you should handle the possibility if the operator implementation in vector does not.

I want to split these two different lines up into words so then I can compare them. To see which is in one and not in the other. Should I be splitting them up and putting them into vectors or arrays? I dont think if if just split them into tokens that will work, or will it?

Tackle one thing at a time. Figure out how to split the line into words and stick them in a vector first and then display the vector, then worry about comparing them later. As far as vectors or arrays, as I mentioned earlier, it can be either, but pick one and stick with it. I'd pick vector. Like I said, there's more than one way to split the line. Look at my links, and Alex put up a good link, plus his snippet. Start playing around with them. You need to develop a game plan of how to separate the line and parse through it. Figure out what a "word" is and figure out what might separate words from each other. From that, extract individual words and make strings out of them, and stick 'em in the array.

commented: Yes, I agree. Always follow through with a decision chosen. +4

Split the lines up into words and place the words for a corresponding line into a vector.

For example, vector<string> a has elements "I", "believe", "in", "you" and vector<string> b has elements "You", "believe", "in", "you".

If you use a == b it will return false because the first element in a isn't equal to the first element in b.

The way the values are compared are defined in the vector's equal operator which is explained here
and more thoroughly explained in this link.

Edit: I do not know if the vector class handles the exception between unequally lengthed vectors, but in the event that you obtain a set of words that are more or less than the vector to be compared against, you should handle the possibility if the operator implementation in vector does not.

I'm a big believer that when first learning, you should do the comparisons yourself directly rather than use many of the very good functions that are provided by C++. Take two vectors. Compare the size. If they're not the same, the vectors are different. Then loop through the vectors and compare each element from the vectors to each other (i.e. 2nd element of first vector to second element of second vector). If any are different, the vectors are different. Once one is very familiar with that, then start using the vector's equal operator and other such things. They're definitely useful, but I think that when one delves directly into these more advanced functions before doing it themselves successfully originally, it leaves a gap in understanding. I feel the same way about using the sort function that's provided by C++. Just my two cents. Others may disagree.

If you just want to compare the two lines you don't need to split them into words. Just compare the entire line

std::string line1;
std::string line2;
getline(myfile, line1);
getline(myfile, line2);
if( line1 == line2 )
{
    // the two lines are identical
}
commented: Very true =P +4

alright thanks for all the help!

Oh, and in case it hasn't been addressed my tokenizer makes tokens out of substrings, not char's.

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.