You are here:

C++/Regarding reading text files in C++


QUESTION: Hi Joydeep,

I have a small question regarding accessing the text files in C++. Here is what I am writing in C++. Tha algorithm is as follows:
for j = 2:length(image)
         Red = image(j,1)+1;
where "image" loads/contains a text file and this text file is filled with strings seperated by tab. So how do i write the above algorithm in C++ to achieve the same effect.
As the total text file gets parsed, I need to display the content accordingly i.e. the specified row/columns it is reading.

Any help in this would be appreciated.


ANSWER: Hi Rishi

Firstly create a two dimensional array to store the strings in it then open the file

fp = fopen("filename","mode");

read it until you get the end of the file
char x[100][100];
int i=0;
int j=0;
char ch;
FILE fp;

 // Now copy a single character using
 ch = fgetc(fp)
  { x[i][j]='\0'; j++; i=0; } // separated by a tab

Now you have got all the strings in the two dimensional array x now enjoy ...

In case if you have any problem with the logic please feel free to ask me or you may join me up at also my personal website for more question

Joydeep Bhattacharya

---------- FOLLOW-UP ----------

QUESTION: Hi joydeep......

Though you could answer my question, still I have a large set of questions and doubt how can I apply above to my part of the code.

I will put down the algorithm that I have written in detail, by which I can put down better understanding. My algorithm is:

Hist = load(fName); /*loads a text file, the text file contains numbers seperated by tab(4 columns)*/
img_3D[][][] = {};//a 3D Array
count = 0;
for j = 2:length(Hist)
         rel_a = Hist(j,1)+1;
         rel_b = Hist(j,2)+1;
         rel_c = Hist(j,3)+1;
         count = imageHist(j,4);
         img_3D(rel_a,rel_b,rel_c) = count;

I need to write the above algorithm in C++ and stuck on how to proceed.

Any help is really appreciated, as this is my student project.

Please help me write code for this part.


Hi Rishi

I don't have so much time now to write the entire program but would be doing it soon and sending it to you.

What I can understand from your problem is that you want to parse a file and get all the numbers stored there.

I have written a program long back to parse a file containing floats and storing it in a two dimensional array that might prove helpful to you for the time being look at this

In case of any help please get back to me for the logic and any other stuff required

Joydeep Bhattacharya


All Answers

Answers by Expert:

Ask Experts


Joydeep Bhattacharya


TSR, Socket and Very Complex Mathematical Problem


Worked on many OOP projects with design patterns



Master of Computer Applications

Awards and Honors
Being a proud owner of a website of programming called

Past/Present Clients

©2016 All rights reserved.