View Single Post
Join Date: Oct 2008
Posts: 44
Reputation: zalezog is an unknown quantity at this point 
Solved Threads: 11
zalezog zalezog is offline Offline
Light Poster

Re: read line of text from file into array

 
0
  #6
Jan 15th, 2009
Originally Posted by AdRock View Post
Thanks zalezog

I'm actually getting somewhere.

It does loop through each of the lines but it only outputs the first "token" on each line

This is an example of what i need to get from my file

1.4 0 0.5
2.3 1.7 0.1
0.8 0 0
0.7 1.0 0.2
1.2 1.3 0.5

Is there a way of tweaking the code cos the output is going to be changed later anyway but I need to get the first line into the array pointers [0][0], [0][1],[0][2] etc and the same for the other lines so i can select 2 array pointers and an display the contents
If you want the whole line to be printed ,then replace every call with..
  1. pch=strtok(str,"\n");

I don't understand,when you say
tweaking the code
If you want to store each word in your file(if that's what you mean)
then something like this might help:
  1. //fragment code
  2. string get_content[10][BUFSIZ];
  3. string words_per_line[5];
  4. //if memory isn't your constraint
  5. //if there are 10 lines in your file
  6. //and if there are more than 5 words in your file
  7. int count_line=0;
  8. int count_word=0;
Then update them in your 'while' loop

  1. while(getline(filename, line))
  2. {
  3. for(int i=0;line[i];++i)
  4. str[i]=line[i];
  5.  
  6.  
  7. char * pch=NULL;
  8. char str[BUFSIZ]={0} ;
  9.  
  10.  
  11. pch = strtok (str," ");
  12. count_word=0;//reset after each line
  13. while (pch!=NULL)
  14. {
  15.  
  16. get_content[count_line][count_word]=pch;
  17. pch = strtok (NULL, " ");
  18.  
  19. array_words[count_line]=++count_word;
  20. }
  21. ++count_line;
  22. }
and display them using loops whose control variables are
count_word
count_line
Reply With Quote