views:

54

answers:

2

Hello, this is an implementation of length indicator field but it hang and i think stuck at a loop and don't show any thing.

// readx22.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
#include "fstream"
#include "stdio.h"
using namespace std;


class Student
{
public:
 string id;
 size_t id_len;
 string first_name;
 size_t first_len;
 string last_name;
 size_t last_len;
 string phone;
 size_t phone_len;
 string grade;
 size_t grade_len;
 void read(fstream &ven);
 void print();
};
void Student::read(fstream &ven)
{
 size_t cnt;
 ven >> cnt;
 id_len=cnt;
    id.reserve( cnt );
    while ( -- cnt ) {
        id.push_back( ven.get() );
    }

 ven >> cnt;
 first_len=cnt;
    first_name.reserve( cnt );
    while ( -- cnt ) {
        first_name.push_back( ven.get() );
    }

 ven >> cnt;
 last_len=cnt;
    last_name.reserve( cnt );
    while ( -- cnt ) {
        last_name.push_back( ven.get() );
    }

 ven >> cnt;
 phone_len=cnt;
    phone.reserve( cnt );
    while ( -- cnt ) {
        phone.push_back( ven.get() );
    }

 ven >> cnt;
 grade_len=cnt;
    grade.reserve( cnt );
    while ( -- cnt ) {
        grade.push_back( ven.get() );
    }

}
void Student::print()
{
// string::iterator it;
 for ( int i=0 ; i<id_len; i++)
  cout << id[i];

}
int main()
{
 fstream in;
 in.open ("fee.txt", fstream::in);
 Student x;
 x.read(in);
 x.print();
 return 0;
}

thanks

A: 

If I understand your question correctly, you are seeing an infinite loop when you run this?

I'd be curious to know what cnt is before each loop.

Also, does your code actually make it to x.print()?


Also, this sounds like a great time to take out a debugger and run it on your code. If it is an infinite loop, a debugger will very quickly tell you where you are stuck.

sharth
yes,i see infinite loopcnt reads how long the string is for example: 4wine cnt reads 4 and use it to read the string no i think the infinite loop exist in x.read()
cj
+2  A: 

You probably should have used cnt-- instead of -- cnt everywhere. The first zero-byte string will trigger an extremely large loop that eventually consumes all memory (except maybe on a 64-bit OS). Actually, don't even bother with this fix. Loop over get() is extremely inefficient, just call read().

Marcelo Cantos
thanks ,it works
cj
Glad to be of assistance. Would you please up-vote and/or tick to accept my answer?
Marcelo Cantos
+1 since cj might forget.
erisco
Thanks all. :-)
Marcelo Cantos