I've implemented a version of the String class (named Str) and I was implementing the getline fucntion of the getline function

that's what I got

void* getline(std::istream& is, Str& s){
	s.clear();
	char c;
	if(is){
		while(is.get(c))
			s.push_back(c);
		return s.begin();
	}
	return NULL;
}

I used void* so I would be able to use the function in a while loop where I was using a string(to test the function).

The function works but no in the same fashion, can someone help me figure out how can I improve my implementation?

Here's the loop:
(PS: split is a function that divides the input into words 'jumping' the spaces)

vector<string> v;
	string test;

	while(getline(cin, test)){
		v = split(test);
		copy(v.begin(), v.end(), ostream_iterator<string>(cout, "\n"));
	}

when I use a string everytime I press enter it copies all the words from the vector, then I enter more words ... etc etc etc.
When I use my Str version of getline I press enter and it just adds the words to the vector ... and then it will only copy the words from the vector when I end the loop ... displaying all the words I've entered so far.

Recommended Answers

All 2 Replies

You have no breaking condition in your getline function. The while loop that uses is.get(), when applied to the standard input stream, will never end. Normally, this loop would end when you hit the end-of-file, but cin never reaches that point, it has no end. When there is nothing remaining on the input stream, the get function will just wait forever. Why not implement a true replacement to the getline function:

std::istream& getline(std::istream& is, Str& s, char delim = '\n'){
	s.clear();
	char c;
	if(is){
		while((is.get(c)) && (c != delim))
			s.push_back(c);
	}
	return is;
}

You have no breaking condition in your getline function. The while loop that uses is.get(), when applied to the standard input stream, will never end. Normally, this loop would end when you hit the end-of-file, but cin never reaches that point, it has no end. When there is nothing remaining on the input stream, the get function will just wait forever. Why not implement a true replacement to the getline function:

std::istream& getline(std::istream& is, Str& s, char delim = '\n'){
	s.clear();
	char c;
	if(is){
		while((is.get(c)) && (c != delim))
			s.push_back(c);
	}
	return is;
}

Thx that was pretty useful ... I didn't know why that was happening ... thx man!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.