Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mmmdreg

macrumors 65816
Original poster
Apr 14, 2002
1,393
0
Sydney, Australia
Hey this is really basic and I don't see why I can't do it but hey. I want something that will read in input until a blank line is entered (ie return is pressed twice).
Code:
	string inputText = "";
	int finish = 0;
	char tempInput;
	
    cout << "Type the text. To end, type a blank line.\n";
	
	while (finish < 2) {
		tempInput = getchar();
		
		if (tempInput != '\n') {
			finish = 0;
			inputText = inputText + tempInput;
		}
		else //if (tempInput == '\n')
		{
			finish++;
		}
	}
The idea is that if there is one blank line, "finish" is incremented. If another, it goes to 2 and the while loop ends. If anything else is entered, it should reset to 0.

Initially, I was trying to use getline but I don't think you can use two characters as thing that terminates it (ie getline(a, b, "2x \n in here)). Apart from that, it worked perfectly.

So any help would be appreciated.
 
I would guess that there is a hidden character that you aren't expecting being inserted before the '\n' character. If I remember correctly, it's probably the line feed character. To do text input, I'd recommend using cin anyway. You're already using cout, why not stick to C++ streams. ;)

Make sure to declare enough memory for your input as well. As defined, you're only allowing 1 character. You code above could actually go out of bounds pretty easily.
 
I thought you can't input a whole lot of stuff using cin.. I've only been doing this for a bit so correct me if I'm wrong.
 
try this

if (tempInput != '\n' && tempInput != '\r') {
...
} else if (tempInput == '\n') {
...
}

Return sometimes triggers two characters \r\n or \n\r depending on platform.

You can use cin to read a lot of stuff including strings and numbers, but cin will just skip whitespace ( \n\r\f\t) so it will not be possible to detect a double return using cin.

I don't think the code will go out of bounds because it uses the string class, but I haven't really used the string class, so I'm not 100% sure.
 
gekko513 said:
try this

if (tempInput != '\n' && tempInput != '\r') {
...
} else if (tempInput == '\n') {
...
}

thanks for your idea. Unfortunately it didn't work =(
I don't know how to debug properly but from test cout things, it seems that the program keeps going through "finish = 0" and so well keep on looping..even when using both \n and \r..

I tried using getline just then, and the result was the same as the above example with the "finish = 0" commented out. Pretty much, it works if two newlines are inputted together in the first instance of a newline.. but it doesn't work if i type something, newline, type something, then do two newlines..

ie:
this works:
blah blah blah
\n\n

but this doesn't:
blah blah blah
\n
blah
\n\n
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.