View Single Post
Join Date: Jan 2008
Posts: 3,750
Reputation: VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute VernonDozier has a reputation beyond repute 
Solved Threads: 491
Featured Poster
VernonDozier VernonDozier is offline Offline
Senior Poster

Re: read line of text from file into array

 
0
  #5
Jan 14th, 2009
Originally Posted by AdRock View Post
I'm trying to get each line of text of a file split into words and then put into an array

I found an exmaple oc cpluscplus.com and their example works but when i try to edit to make changes to read the line of text from a file i get an error on this line:
  1. char str[] = getline(filename, line);

error message:


I need to be able to read in a line and spilt the words into an array so i can output them

  1. #include <fstream>
  2. #include <iostream>
  3. #include <string>
  4. #include <stdio.h>
  5.  
  6. using namespace std;
  7.  
  8. int main()
  9. {
  10. string GetFileName;
  11.  
  12. cout << "System >> Enter file to read: \n";
  13.  
  14. cout << "User >> ";
  15. cin >> GetFileName;
  16.  
  17. ifstream filename( GetFileName.c_str() );
  18.  
  19. if(! filename )
  20. {
  21. cout << "Unable to open file: " << GetFileName << endl;
  22.  
  23. return EXIT_FAILURE;
  24. }
  25. else
  26. {
  27. while (getline(filename, line)) //Loop through lines
  28. {
  29. char str[] = getline(filename, line);
  30. char * pch;
  31.  
  32. pch = strtok (str," ");
  33. while (pch != NULL)
  34. {
  35. printf ("%s\n",pch);
  36. pch = strtok (NULL, " ");
  37. }
  38. }
  39. filename.close();
  40. }
  41. return EXIT_SUCCESS;
  42. }

Is this the whole program? I don't see where line is declared. You have two getline statements when you only need one.

  1. while (getline(filename, line)) //Loop through lines
  2. {
  3. char str[] = getline(filename, line);

The second one, even if it was syntactically correct, which it is not, overwrites line , which I imagine is supposed to be a string.

You can use char* or string with getline:

http://www.cplusplus.com/reference/i...m/getline.html
http://www.cplusplus.com/reference/string/getline.html

The links above have examples of each.
Reply With Quote