CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2008
    Posts
    17

    why is the loop started a third time?

    conff is an opened file which contains 4 lines only
    Code:
    	    short int nubses = 0; string line;
    	    while (conff)
    		{
    		getline(conff, line); OPT[nubses] = line.substr(4, line.size());
    		getline(conff, line); OPT_Vuln[nubses] = line.substr(9, line.size());
    		nubses++;
    		}
    but the program goes into the loop a third time and crashes... why? it should be end of file

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725

    Re: why is the loop started a third time?

    I find that it is usually best to code these loops as follows:

    Code:
    while (getline(conff, line))
    {
       OPT[nubses] = line.substr(4, line.size());
       getline(conff, line); 
       // should probably check stream state here also
       OPT_Vuln[nubses] = line.substr(9, line.size());
       nubses++;	
    }

  3. #3
    Join Date
    Aug 2005
    Location
    LI, NY
    Posts
    576

    Re: why is the loop started a third time?

    failbit, badbit, and/or eofbit are not set until after an input operation fails, so you'll need to check after each call to getline to make sure that data was actually extracted from the stream.

    I think the following should work:
    Code:
    short int nubses = 0; string line;
    while (!conff.eof())
    {
    	if (getline(conff, line))
    		OPT[nubses] = line.substr(4, line.size());
    
    	if (getline(conff, line))
    		OPT_Vuln[nubses] = line.substr(9, line.size());
    
    	nubses++;
    }
    EDIT: I like Philip's version better.
    Last edited by Hermit; August 11th, 2008 at 01:25 PM.
    - Alon

  4. #4
    Join Date
    Jul 2008
    Posts
    17

    Re: why is the loop started a third time?

    thx a lot guys

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured