How to check for blank line?

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
jongooni
New poster
Posts: 4
Joined: Thu Jul 05, 2007 5:43 pm

How to check for blank line?

Post by jongooni » Fri Jul 06, 2007 4:23 am

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

jan_holmes
Experienced poster
Posts: 136
Joined: Fri Apr 15, 2005 3:47 pm
Location: Singapore
Contact:

Post by jan_holmes » Fri Jul 06, 2007 10:31 am

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());
          printf("%d\n",n);
    }
    return 0;
}

jongooni
New poster
Posts: 4
Joined: Thu Jul 05, 2007 5:43 pm

Post by jongooni » Fri Jul 06, 2007 4:31 pm

Actually for some reason that doesn't sem to work when I do something like

1
//doesn't see this blank line
2
//doesn't see this blank line
4

chunyi81
A great helper
Posts: 293
Joined: Sat Jun 21, 2003 4:19 am
Location: Singapore

Post by chunyi81 » Fri Jul 06, 2007 6:23 pm

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.

jongooni
New poster
Posts: 4
Joined: Thu Jul 05, 2007 5:43 pm

Post by jongooni » Fri Jul 06, 2007 6:39 pm

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.

User avatar
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba » Fri Jul 06, 2007 11:39 pm

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).
For millions of years, mankind lived just like the animals. Then something happened which unleashed the power of our imagination. We learned to talk and we learned to listen...

Post Reply

Return to “C++”