devxlogo

Be Careful Using std::cin.getline() and std::cin >> var Together

Be Careful Using std::cin.getline() and std::cin >> var Together

If you provide std::cin.getline() with a third argument?a “stop” character, it ends its input by eating the character and terminating the string. For example:

std::cin.getline(str, 100, '|') 

Without this this argument, std::cin.getline() stops when it reaches a new line. For example:

float fl;std::cin >> fl;char str[101]std::cin.getline(str, 101);cin.ignore();

And you type:

3.14 

3.14 is read into fl. The new line following the 3.14 still sits on the input buffer.

std::cin.getline(str, 101) immediately processes the new line still on the input buffer. str becomes an empty string.

The illusion here is that the application “skipped” the std::cin.getline() statement.

The solution is to add std::cin.ignore(); immediately after the first std::cin statement. This grabs a character off of the input buffer (in this case, newline) and discards it.

You can call std::cin.ignore() three different ways:

  1. No arguments: Take a single character from the input buffer and discard it:
    std::cin.ignore(); //discard 1 character 
  2. One argument: Take a specified number of characters from the input buffer and discard them:
    std::cin.ignore(33); //discard 33 characters 
  3. Two arguments: Discard the number of characters specified or discard characters up to and including the specified delimiter (whichever comes first):
    std::cin.ignore(26, '
    '); //ignore 26 characters or to a newline, whichever comes first 
See also  5 Benefits of Using Time Tracking Software
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist