Search code examples
c++arraysstringcingetline

Ignore() function usage issue in c++


#include <iostream>
#include <ios> 
#include <limits>

using namespace std;

int main() {
   int x;
   char str[80];
   cout << "Enter a number and a string:\n";
   cin >> x;
   cin.ignore('\n');

   cin.getline(str,80); 
   cout << "You have entered:\n";
   cout << x << endl;
   cout << str << endl;
}

I am facing an issue with the ignore function where using cin.ignore('\n'); results in an output where I have to press Enter multiple times to print statements (for less number of characters) or else it cuts some of the initial characters from my string in the output (in case of more number of characters). Like these:

image

image

while using cin.ignore(); results in the correct output.

image

Isn't it the same to use either of these as '\n' discards new line character and an () empty bracket also dicards the last character (or new line character as here).

Also, when should we use cin.getline() and getline(cin, )?


Solution

  • You are using ignore() incorrectly.

    It has 2 optional parameters - a max count of characters to ignore, and a delim character to stop ignoring on, in that order:

    basic_istream& ignore( std::streamsize count = 1, int_type delim = Traits::eof() );
    

    ignore() will skip characters until the delim is encountered, or the count has been reached, whichever occurs first.

    You are passing '\n' to the count parameter, not the delim parameter. '\n' has a numeric value of 10 when converted to an integer. So you are telling ignore() to skip 10 characters.

    In your 1st example, that is the line break after 6, followed by the next 9 characters gautamgoy. Thus the getline() afterwards starts reading at al and ends on the next line break.

    In your 2nd example, that is the line break after 4, followed by the next 6 characters grgzed, followed by the next 3 line breaks. Thus the getline() afterwards ends on the next line break as there are no characters to read.

    In your 3rd example, calling ignore() with no parameters will skip only 1 character, the line break after 6, leaving the rest of the characters gautam goyal for getline() to read up to the next line break.

    When ignoring characters up to the next line break, regardless of how many characters there are, use this instead:

    #include <limits>
    
    cin.ignore(numeric_limits<streamsize>::max(), '\n');