Re: Read from txt file

From: Jon Bell (jtbellj3p_at_presby.edu)
Date: 01/26/04


Date: Mon, 26 Jan 2004 16:51:41 +0000 (UTC)

In article <401543ba$0$95068$edfadb0f@dread11.news.tele.dk>,
JrdA <n@n.n> wrote:
>
>Now i have a txt-file containing :
>
>1234#01/26/04#
>424#01/26/04#
>324234#01/26/04#
>
>I then need ifstream to read the first ints until it reaches the # sign and
>then add them togheter.

I assume you don't need to do anything with the rest of the data on each
line.

When you read an int using >>, it will stop reading when it reaches the
first character that cannot be part of an int, so it will stop at the
first # sign. Now now you need to skip over the rest of the line, which
you can do with ignore().

ifstream input ("your.file");
int num;
while (input >> num)
{
   // do whatever you need to do with num here

   input.ignore (1000, '\n'); // skips past next newline, or 1000 chars,
                               // whichever comes first
}

Depending on the maximum posslbie line length in your file, adjust the
1000 if necessary.

-- 
Jon Bell <jtbellm4h@presby.edu>                     Presbyterian College
Dept. of Physics and Computer Science        Clinton, South Carolina USA


Relevant Pages

  • Re: unique numbers using srand( ) and rand( ) functions in C++[ caution long post]
    ... /*for declaring objects of the ofstream and ifstream classes for a data ... int main ... /*consume # character betwwen numbers of each record in data file or the ... return SUCCESS; ...
    (alt.comp.lang.learn.c-cpp)
  • Re: std::ifstream
    ... "David Wilkinson" wrote: ... If I pass to my ifstream object a constant filePath ... int linesCount; ...
    (microsoft.public.vc.language)
  • Slow ifstream close when accessing network files
    ... The code in question opens an ifstream, calls seekgwith a non zero value, ... unsigned int threadHandle = 0; ... ifstream *ifs; ... void TestFileAccess2{ ...
    (microsoft.public.vc.stl)
  • Re: std::ifstream
    ... If I pass to my ifstream object a constant filePath it works, but it doesn't as soon as I pass it a variable. ... int linesCount; ... You have to use c_strmember to get const char* from a string; ...
    (microsoft.public.vc.language)
  • Re: Question...
    ... pass-by-value argument of type ifstream. ... Again, ifstream has no copy constructor, so you can't assign one ifstream to ... Main *always* returns int. ... argc will contain the amount of parameters, argv is an array than contains ...
    (comp.lang.cpp)

Loading