[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: [OT] C++ programming: keeping count of data items read from file

Jordi Gutiérrez Hermoso wrote:
On 06/05/2008, H.S. <hs.samix@gmail.com> wrote:
 Yup, that fscanf method looks interesting. I used that only when I program
in C, but it might be judicious to use it in C++ in this situation.

It's not. Streams are better and keep you away from nasty errors and segfaults.

Use getline(istream, string).

Suppose ifs is some istream (e.g ifstream ifs("file.data");).

Then you do something like

      string s;
          stringstream ss;
          ss << s;
          double x;
          list this_line;
          while(ss >> x){
              // Read the doubles one by one into some data structure
           if(this_line.size() != rows){
              //Handle error here somehow

If you need more fine control than this, you use boost::tokenizer.

- Jordi G. H.

Hmmmm... Well, fscanf() *is* evil. And subject possibly to buffer overflows. But understandable to an old fart. Who still has _A Book on C_ and Kernighan and Ritchie lying around somewhere. (And should have looked it up to see if it was really suitable.)

Streams *are* better. But I would rather statically link to stdio than to iostream, if the subject ever comes up, and the choice has to be made.

Fortunately, I don't have to write this code anymore. So I can cheerfully forget how it works, and post red herrings while kibitzing. (I could claim that I thought of it, but just didn't post an example because I couldn't think of the getline() function. But I won't make that claim, because it wouldn't be believed.)

Mark Allums,

Who mostly writes code in lua these days, when he writes any at all.

Mark Allums

Reply to: