this simple cout statement and i do not know why. the outputs are mixed up and i get some random numbers i didnt even input.please help

#include <iostream>
#include <string>
using namespace std;

int main()

{
	
	string Pname, CEmployer;
	int age;
	

	cout<<"Patients Name:"<<endl;
	getline (cin, Pname);


	cout<<"Age:"<<endl;
	cin>>age;

	cout<<"Current Employer"<<endl;
	getline (cin, CEmployer);




cout<<Pname<<endl;
cout<<age<<endl;
cout<<CEmployer;


};

Recommended Answers

All 7 Replies

After line 19 you need to flush the input buffer of the '\n' character. cin.ignore(1000,'\n'); should do the trick.

commented: very helpful +1

thanks alot!!
would i have to flush the input buffer after every other
time so it wont happen again?

When a cin >> is followed by getline( ), you will need to use the ignore( ) function in between. You normally don't need the ignore( ) between two input statements of the same type.

commented: thanks for the help +1

>You normally don't need the ignore( ) between two input
>statements of the same type.

Or when the getline() is before the cin>>.

commented: thanks for the help +1

>You normally don't need the ignore( ) between two input
>statements of the same type.

Or when the getline() is before the cin>>.

But when you do such reading in a loop, what comes before what?

while ( getline( cin, str ) )
{ 
      cin >> num;
      //do something with them

     //oops, need the cin.ignore( ) here
}

Good point !

There's an extensive thread about flushing the input stream, you can find it here ...

commented: thanks for the help +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.