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.
How to read each line of a file to array?
Collapse
X
-
Matt FTags: None -
You should use something like this (c++)
Code:#include <fstream> #include <iostream> #include <vector> #include <string> using namespace std; int main(){ ifstream ifs; ifs.open("filewhatever.txt"); string dat; vector<string> vecstring; while(getline(ifs, dat)) vecstring.push_back(dat); return 0; } -
C code goes like this:
Code:#include<stdio.h> int main(int argc,char *argv[]){ int i=0; arr[20][50];//20 is no of line, 50 is length of line FILE *fp; fp=fopen(argv[1],"r"); if(fp==NULL) { printf("Unable to open file %s",argv[1]); exit(1); } while(fgets(&arr[i][0],50,fp)!=NULL) i++; return 0; }Comment
Comment