Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Why does my std::getline() read blanks? Why do I need to press the enter key twice whenever I use std::getline() in VC++? How do I fix those problems?

VC++ Problem

Why does my std::getline() read blanks? Why do I need to press the enter key twice whenever I use std::getline() in VC++? How do I fix those problems?

by  Zech  Posted    (Edited  )
Q: Why does my std::getline() read blanks?

A: Actually, your std::getline() does not read blanks. Instead, it reads the leftover delimiter (such as '\n' or ' ') from the previous input stream operation. Usually it happens when you use "cin>>buffer" followed by a call to "getline()".

Consider the following stream of data:

"I am so confused."

Code:
cin>>buffer_1;
getline(cin,buffer_2);

cin will read 'I' but it does not read the white space ' ' following 'I'. Thus, buffer_1 will store 'I' and buffer_2 will get the white space ' ' between 'I' and am. That's why you get blanks for your buffer_2.

Solution:
Use cin.ignore() to ignore the unwanted delimiter.

Code:
cin>>buffer_1; [green]//buffer_1="I"[/green]
cin.ignore(1,' '); 
getline(cin,buffer);[green]//buffer_2="am so confused."[/green]

Q: Why do I need to press the enter key twice whenever I use std::getline() in VC++?

A: There is a bug in VC++'s implementation of string. This has been posted for quite sometimes by Microsoft at http://support.microsoft.com/default.aspx?scid=kb;en-us;240015 Thus, VC++'s std::getline() will read an extra character after encountering a delimiter.

Solution:
Go to your include folder (typically it can be found at C:\Program Files\Microsoft Visual Studio\VC98\Include) and edit STRING. [red]NOTE that the file name is STRING and not STRING.H[/red]. Make the changes as mentioned in the article.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top