You are here:

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

Advertisement


Question
QUESTION: Hi Amit,

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.

Thanks,
Rishi


ANSWER: I dont understand the algorithm you have mentioned. Maybe you could explain it a bit better to me. Provide an example input and output as well.

Anyway, for reading text from file, you can use iostream. See http://www.cplusplus.com/doc/tutorial/files.html If that does not help, write to me again.

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

QUESTION: I would like to read a text file, the text file contains a set of rows and columns..., i need to read the text file with the following format (row,column) and each of that value into a variable "red".

Thanks,
Rishi

Answer
you could do something like:

#include <fstream>
#include <string>
#include <cassert>

std::fstream f("text file");
int row = 0;
int col = 0;
while(f) {
  std::string str;
  f >> str;
  image[row][col] = str;
  if(col = total_num_cols - 1) { col = 0; row++; }
  else col++;
}  
assert(row == total_num_rows);
assert(col == total_num_cols);

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Amit Kumar

Expertise

I can answer Cplusplus language and library questions, including STL, ACE, Boost. I have a good background in Mathematics.

Experience

Programming in CPP for about 8 years. Industry experience of 4 years.

Education/Credentials
Bachelors and Masters in Computer Science from Indian Institute of Technology Delhi.

©2016 About.com. All rights reserved.