Jump to content


Photo
- - - - -

C++ File Reading


  • Please log in to reply
2 replies to this topic

#1 c0ld

c0ld

    Member

  • Members
  • PipPip
  • 122 posts
  • Gender:Male

Posted 14 December 2004 - 02:56 PM

How do you get file input stream to detect the end of a line?
If I have a file that looks like this:
Jim
80 90 100
Joe
70 80 90
And wanted output (cout) to look like this:
Jim: 90
Joe: 80
With those numbers being the averages of Jim's three and Joe's three respectively, how would I get the program to detect the new line? If there was some special character to denot the end of a set of numbers, I could do it, but there is not, so I cannot. :(
5^.5*.5+.5

#2 markiemrboo

markiemrboo

    BSD Fiend

  • Members
  • PipPipPipPipPipPip
  • 5955 posts
  • Gender:Male
  • Location:Gt Yarmouth, UK

Posted 14 December 2004 - 03:14 PM

Well \n is a newline character, so search for that I would guess (you could use strrchr for doing something like that).

Otherwise, why not use fgets? :)

"
The fgets() function reads at most one less than the number of characters
specified by size from the given stream and stores them in the string
str. Reading stops when a newline character is found, at end-of-file or
error.
"
( Intel C2Q9300 + Scythe Zipang (400 x 7.5 = 3GHz @ 1.3v) ) ( Gigabyte GA-P35C-DS3R v2.1 ) ( 2 x 2GB OCZ OCZ2N800SR4GK PC2-6400 (400 x 5-5-5-15 @ 2.1v) ) ( Sapphire 4890 OC 1GB ) ( 4 x 1TB Samsung F1, 1 x 500GB Samsung T ) ( Pioneer DVR-109XL ) ( X-fi XtremeMusic ) ( Corsair HX 520 ) ( Enermax Pandora CA-3030 ) ( 2 x Benq G2400W ) ( Cherry CyMotion Expert ) ( Windows Vista Ultimate x64 SP1 )

Posted Image

#3 LobbDogg

LobbDogg

    Hey kid, I'm a computer, Stop all the downloading!

  • Members
  • PipPipPipPipPip
  • 2421 posts
  • Location:Edmonton, AB

Posted 14 December 2004 - 05:41 PM

another way to do it is

#include <fstream.h>



ifstream datafile;  
datafile.open("a:gradesin.dat");



for (i=0;!datafile.eof();i++)

This will read in one line at a time using a for loop, of course you can implement it in a while loop or whatever.

Edited by LobbDogg, 14 December 2004 - 05:42 PM.