Thread: Read a line and go back to start

  1. #1
    Registered User
    Join Date
    Oct 2008
    Posts
    84

    Read a line and go back to start

    Hi,

    I'm trying to create a 3d model loader, so one part requires me count the number of '/' in a line and store it. After that I need to go back to the start of the line so I can get the data.

    Here is what I'm trying to do. It seems to work for about 20-30 lines and then corrupts the file. Can anyone see why this approach might cause an error ? or have a better way of doing what I'm trying to do ?

    Code:
                            int numVerts = 0,u = 0;
    			char c;
    
    			while((c = infile.get()) != '\n'){
    				if(c == '/') ++numVerts;
    				++u;
    			}numVerts /= 2;
    
    			for(; u >= 0; --u){
    				infile.unget();
    			}
    Thanks!

  2. #2
    Registered User
    Join Date
    Oct 2008
    Posts
    84
    Anyone ?

    Also, I added an assert after the for loop ->
    Code:
    assert(infile.good());
    and it does fail after about 20 lines, I checked the file and it seems to be fine.

    Any Ideas ?

  3. #3
    Registered User
    Join Date
    Jan 2010
    Posts
    30
    You could read an entire line into a char array, then process it from there, instead of using "unget".

    So, for example, you could, say...

    Code:
    int i, len, numVerts = 0;
    char buffer[10000];
    
    infile.getline(buffer, 10000, '\n');
    len = strlen(buffer);
    
    for(i=0; i<len; i++){
      //do your counting here
    }
    
    //all your data in that line is now in "buffer"
    //say if you would still like to read the data as a stream, then you could use the class
    //strstream
    
    istrstream in(buffer);
    
    //you could read from the stream "in" in the same way as you do from "infile".

  4. #4
    Registered User
    Join Date
    Oct 2008
    Posts
    84
    Aah, Worked like a charm!

    Thank you so much!

    But If anyone knows, I would still like to know why my previous code failed ?

  5. #5
    Registered User
    Join Date
    Jan 2010
    Posts
    30
    Well, first of all, I am always wary of things like "unget" and stuff. I've had some bad experience with those.
    And, for your case, I think your second loop iterates one more time than necessary.
    Say you have N characters in a line, then at the end of the first loop, u = N.
    Now if you loop u from N to 0, you get (N+1) iterations, instead of N.
    What you should have done is to change the guard condition of the loop to "u>0".

  6. #6
    Registered User
    Join Date
    Oct 2008
    Posts
    84
    Ah, you are right about the u > 0 condition, that was a typo. Although even if I switch it to u > 0, the stream still fails. I had never used unget() in c++ before so I thought I would try it since I'm used to the ungetch() in c.

Popular pages Recent additions subscribe to a feed