debonair
debonair

Reputation: 2593

break loop when empty string entered in C++

I am taking a string input from the user. Following is my code

cout<<"enter the number of strings";
cin>>size;
int i=0;
while(i<size)
{
     string input="";
     cin.ignore();
     getline(cin,input);
     if(input.empty())
           break;
      i++;
}

I want to terminate the program when I give input as newline character (blank string). But above code runs for one extra counter. Where I am going wrong ?

Upvotes: 0

Views: 3756

Answers (2)

PlaceUserNameHere
PlaceUserNameHere

Reputation: 126

Place cin.ignore outside the while, just before it

Here's the code

int main(){
    int size;
    cout<<"enter the number of strings";
    cin>>size;
    int i=0;
    cin.ignore();
     while(i < size)
    {
     string input="";
     getline(cin,input);
     if(input == "")
           break;
      i++;
    }
}

Upvotes: 1

mah
mah

Reputation: 39827

The getline() function returns data including the carriage return, so your input isn't going to actually be empty when a "blank line" is provided.

DESCRIPTION
     The getdelim() function reads a line from stream, delimited by the char-
     acter delimiter.  The getline() function is equivalent to getdelim() with
     the newline character as the delimiter.  The delimiter character is
     included as part of the line, unless the end of the file is reached.

Note also that the function returns the number of characters written to your buffer... you can simply check for that value rather than calling input.empty(), and at the same time you could perform error checking.

Upvotes: 4

Related Questions