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 
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS