Hello everyone this is my first post.

My problem is reading from a text file. The file is in the format: name\tdouble\tdouble\tdouble int

Since I have no control over the format of the file and do not know the size, I first begin by counting the lines of the file(nLineCount2). My question is, is fscanf the best/easiest way to read this file?

Sample of my code:

FILE *f;
	f = fopen(sFileName.c_str(), "r");
	for(int i = 0; i < nLineCount2; i++)
 		fscanf(f, "%s\t%lf\t%lf\t%lf %d", &name[0][i], &Data[1][i], &Data[0][i], &Data[2][i], nType[i]);

The problem I'm running into is how to read the string in. I first made an array of strings, but fscanf needs character strings. Then I made a 2d character array. I can't seem to get either one to work and I'm wondering if fscanf is the way to go. Any input would be great. Thanks in advance.

Well you don't even need to know the number of lines in the file.
Use this :

fstream f_ptr;
string str;

This complies to your requirements when the fields are delimited by some value.

Um, this is a C++ forum. You'll get more and better response in the C forum.

And, csurfer, using eof( ) in that manner is going to unreliable at the end of the file, last value read in could be processed twice. This has been amply discussed on the forum.

Yes vmanes you are right. But the OP had to start somewhere so I thought this would be better to start with and later learning and bettering the code from his/her own mistakes.Even this could be a solution to start with :


But best according to daniweb is to use this:

while(fgets(....)!=NULL){.....} //or to use

Get more info here.

Thanks for the responses. My issue is not with how many lines are in the file, I already have that, it's reading the strings in the first column of the file that is giving me problems. I don't have to use fprintf. I posted here to see if there was a better/easier way to do what I'm trying to do in C or C++. Thanks again.