C++ getline() Does not Work Properly in Visual C++

Asked By 10 points N/A Posted on -
qa-featured

I have this simple statement that I am trying to follow from a book. The code reads:

#include <iostream>
#include <string>
 
using namespace std;
int main()
{
string names;
cout<<"Enter your name:n";
getline(cin, names);
cout<<names<<endl;
return 0;
}
 
I tried running it using the command line and it works. Why is getline() not working in Visual C++? Is there a possible fix for it?
SHARE
Answered By 0 points N/A #108993

C++ getline() Does not Work Properly in Visual C++

qa-featured

 

Hi Bryan,
 
I didn't see any problem with the code you wrote, as a matter of fact, this one works perfectly. 
 
Here's my insights:
 
You said it worked in the command line, so it is certain that you have already built the executable file of your program. If it compiled correctly and no linking error at all, then this must be a simple problem.
 
I tried compiling the code on Visual Studio 2008 and it worked fine! I was able to input the name, but the program exited after I pressed return. Is this the problem you are referring to? If it is, then you just need a line of code to make it behave like the command line.
 
Use this function:
 
int system ( const char * command );
 
The declaration of this function is found in "stdlib.h"
 
#include <iostream>
#include <string>
using namespace std;
int main()
{
string names;
cout<<"Enter your name:n";
getline(cin, names);
cout<<names<<endl;
system("pause"); //- Invokes the command processor to execute a command.
return 0;
}
 
I hope it helped.

Login/Register to Answer

Related Questions