954,506 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Read text file contents per line

Hi I'm creating a parser using Visual C++ and I'm having a problem reading the contents of a file per line. I tried using fread but you have to specify that size of the record you need to store in the buffer. Length of each line record is variable so I can't make use of this function.
It's my first time using Visual C++ and my background in C is little, I had it while I was still in college. I'd really appreciate your help (I already tried one of the suggestions posted here, but it still is giving me some errors!)

Thanks in advance.

sofia24
Newbie Poster
7 posts since Feb 2008
Reputation Points: 10
Solved Threads: 0
 
std::ifstream file( "filename.txt" ) ;
std::string line ;
while( std::getline( file, line ) )
{
   // parse the line which was just read
}
vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287
 

Thanks a lot! :)

sofia24
Newbie Poster
7 posts since Feb 2008
Reputation Points: 10
Solved Threads: 0
 
Nichito
Posting Virtuoso
1,602 posts since Mar 2007
Reputation Points: 424
Solved Threads: 57
 

Thank you so much for your help. I have writed the program to read each input files and two functions. One function is to calculate a output value to each input data based on mathematical formulae. The other function is to manimulate the data in the input file and create output files (text files) to each input file.

I copied yout code and executed it. I had the following error.

[code]
1>------ Build started: Project: acoresult, Configuration: Debug Win32 ------
1>Compiling...
1>checkresult.cpp
1>d:\megala\acoresult\acoresult\checkresult.cpp(26) : error C2664: 'std::basic_ifstream<_Elem,_Traits>::basic_ifstream(const char *,std::ios_base::openmode,int)' : cannot convert parameter 1 from 'std::basic_string<_Elem,_Traits,_Ax>' to 'const char *'
1> with
1> [
1> _Elem=char,
1> _Traits=std::char_traits
1> ]
1> No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1>Build log was saved at "file://d:\megala\acoresult\acoresult\Debug\BuildLog.htm"
1>acoresult - 1 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

[/icode]

Please help me to resolve the issue. I am willing to send you the complete code and input files, if you could help me.
Thank you

maria99
Newbie Poster
10 posts since Jun 2010
Reputation Points: 10
Solved Threads: 0
 

Please create a new thread because this one has already been solved...

Taywin
Posting Virtuoso
1,727 posts since Apr 2010
Reputation Points: 229
Solved Threads: 239
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You