Can anyone see what's wrong with this function?

This is a discussion on Can anyone see what's wrong with this function? within the C++ Programming forums, part of the General Programming Boards category; This function crashes me when I call it, and i can't figure out why. Code: vector<string> line_split(const string& s) { ...

  1. #1
    The Earth is not flat. Clyde's Avatar
    Join Date
    Mar 2002
    Posts
    1,420

    Can anyone see what's wrong with this function?

    This function crashes me when I call it, and i can't figure out why.

    Code:
    vector<string> line_split(const string& s)
    {
    	vector<string> ret;
    	string::size_type size = s.size();
    	int i =0, j=0;
    
    	while (j != size)
    	{
    		while (j != size && s[j] != '\r' )
    			j++;	
    
    		if (i != j)
    			ret.push_back(s.substr(i, j-i));
    		i = j;
    	}
    
    	return ret;
    }
    If I comment out the first while loop, it works, but when I include it, it doesn't. Any ideas?

  2. #2
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    You haven't advanced the counter after finding the newline (infinite loop). Using more standardised syntax, your function might look something like -

    Code:
    vector<string> line_split(const string& s)
    {
    	vector<string> ret;
    	string::size_type size = s.size();
    	unsigned int i =0, j=0;
    
    	while (j < size)
    	{
    		while (j != size && s[j] != '\n' )
    			j++;	
    
    		if (i != j)
    			ret.push_back(s.substr(i, j-i));
    		
    		i = j++;
    		
    	}
    
    	return ret;
    }

  3. #3
    The Earth is not flat. Clyde's Avatar
    Join Date
    Mar 2002
    Posts
    1,420
    Thanks very much

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 07:54 PM
  2. Game Pointer Trouble?
    By Drahcir in forum C Programming
    Replies: 8
    Last Post: 02-04-2006, 02:53 AM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 02:27 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21