Page 1 of 1

How to check for blank line?

Posted: Fri Jul 06, 2007 4:23 am
by jongooni
I'm having trouble figuring out how to read in numbers until I hit a blank line. This is what I have so far, and I've looked into getline and cin and others.

bool keep_going = true;
string z;
int a;
while(keep_going){ //stay in while loop until blank line
getline(cin, z); //read in line
a = z.size() - 1; //get
if( z[a] == '\n'){ //check for blank line
keep_going = false;
}//end if
}//end while

I'm new to c++ so any help is nice

Posted: Fri Jul 06, 2007 10:31 am
by jan_holmes
This might help :

Code: Select all

int main () {
    string s;
    while (getline(cin,s)) {
          if (s.length() == 0) break;
          int n = atoi(s.c_str());
    return 0;

Posted: Fri Jul 06, 2007 4:31 pm
by jongooni
Actually for some reason that doesn't sem to work when I do something like

//doesn't see this blank line
//doesn't see this blank line

Posted: Fri Jul 06, 2007 6:23 pm
by chunyi81
I think what you need is something like this:

Code: Select all

int main()
    string str;
    while (getline(cin,str))
         if (str.length() > 0)
             // process input
    return 0;
This will read until end of file and skips blank lines as well. Hope this helps.

Posted: Fri Jul 06, 2007 6:39 pm
by jongooni
THanks, but I don't want to skip blank lines. I want to stop on blank lines and then process what I just read in.

Posted: Fri Jul 06, 2007 11:39 pm
by Krzysztof Duleba
Do you need it all spell out? You already have tools necessary to accomplish that goal (I'll just add that string::size() method is nicer than string::length()). If you don't, my advice is that you get a good book and read it, your questions indicate lack of basic understanding of programming in general and C++ in particular. (If I'm wrong about that, you should start applying those skills, otherwise you won't progress).