By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,373 Members | 1,763 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,373 IT Pros & Developers. It's quick & easy.

How to read each line of a file to array?

P: n/a
I am trying to read a text file and store each line as a seperate entry in an array. I have tried searching for how to do this but I can only find how to store the whole file into a 1D array.
Oct 21 '10 #1
Share this Question
Share on Google+
2 Replies


JavierL
P: 17
You should use something like this (c++)

Expand|Select|Wrap|Line Numbers
  1. #include <fstream>
  2. #include <iostream>
  3. #include <vector>
  4. #include <string>
  5.  
  6. using namespace std;
  7.  
  8. int main(){
  9.  
  10. ifstream ifs;
  11. ifs.open("filewhatever.txt");
  12. string dat;
  13. vector<string> vecstring;
  14.     while(getline(ifs, dat))
  15.           vecstring.push_back(dat);
  16.  
  17. return 0;
  18. }
  19.  
Oct 22 '10 #2

P: 10
C code goes like this:


Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2.  
  3. int main(int argc,char *argv[]){
  4.  
  5.    int i=0;
  6.    arr[20][50];//20 is no of line, 50 is length of line
  7.    FILE *fp;
  8.  
  9.       fp=fopen(argv[1],"r");
  10.       if(fp==NULL)
  11.     {
  12.       printf("Unable to open file %s",argv[1]);
  13.       exit(1);
  14.     }
  15.  
  16.     while(fgets(&arr[i][0],50,fp)!=NULL)
  17.     i++;
  18.  
  19. return 0;
  20.  
  21. }
Oct 23 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.