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


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

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