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!

getline (cin, str) - simple question

Status
Not open for further replies.

pctek11

Technical User
Feb 12, 2003
5
0
0
US
I'm still rather new to C++ (as the handle infers, I deal more with the tech environment than programming)

My question deals with getline in a regular Win32 Console App. The following is an excerpt of simplified code. It compiles just fine, but I get a Debug Error! in runtime if I execute more than one test at a time.
_________________________________________

#include <iostream>
#include <string>
#include <cstdlib>

using namespace std;

void test1()
{
[tab]string phoneNum;

[tab]cout << &quot;Enter a phone number (x-xxx-xxx-xxxx): &quot;;
[tab]cin >> phoneNum;
//Output format (xxx) xxx-xxxx
[tab]cout << &quot;\nFormatted number: (&quot; << phoneNum.substr(2, 3) << &quot;) &quot;;
[tab]cout << phoneNum.substr(6, 13) << &quot;\n\n&quot;;
}

void test2()
{
[tab]string input, newName;

[tab]cout << &quot;Enter a name:\t&quot;;
[tab]getline(cin, input);

[tab]// formats input to Last, First Middle.
{
[tab].
[tab].
[tab].
}
[tab]cout << &quot;\nThe result is:\t&quot; << newName << endl;
}

void main()
{
[tab]test1();
[tab]test2();
}
____________________________________________


Again, this has been oversimplified for obvious reasons. test1() runs just fine. When test2() executes, Enter a name: is displayed, but a debug error occurs instantly not allowing input. If i run either test by itself, the both execute just fine. I'm assuming that istream is getting corrupted during the transition from test1 to test2.

I have already fixed the string library bug that affects getline, but it didn't help. Aside from using a character array instead ( cin.getline(char[], n) ), is there any reason why this might happen?

TIA,
pctek
 
Well, I found my problem. Looks like I just needed to add a simple cin.ignore(xx, xx) statement at the end of each test.

<sarcastic>
Thanks for all the generous feedback and suggestions!
</sarcastic>
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top