dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: C++
Expertise: Intermediate
Mar 1, 2005

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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<return> 
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, '\n'); //ignore 26 characters or to a newline, whichever comes first 
    
Sudeepa Kumar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
×
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.
Thanks for your registration, follow us on our social networks to keep up-to-date