-
Compiler Problem
Hi all,
I have just started on C++ and am trying to follow the tutorials on this site. However, I've bumped into a problem. I'm doing the example where the user enters a number and then it is returned. Here is my code.
Code:
#include <iostream.h>
int
main()
{
int thisisanumber;
cout<<"Please enter a number:";
cin>>thisisanumber;
cout<<"You entered: "<<thisisanumber;
cin.get();
return 0;
}
When I enter my number and press return, the compiler just closes. I've put cin.get(); in, like explained in a tutorial.
Would it be possible for somebody to help? I've looked in the FAQ but couldn't find anything. I am using Bloodshed.
Thanks very much,
Mike
-
Your use of cin leaves a newline in the stream that cin.get() picks up. The easy solution is to add another cin.get(). A somewhat better solution is to use cin.ignore() with a large enough size to handle any length of extraneous input and a delimiter of '\n'. The best solution is to only use getline to read input as a string and then perform conversions once you have the data in memory. Here is one hybrid approach:
Code:
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
int
main()
{
string buffer;
int thisisanumber;
cout<<"Please enter a number:";
getline ( cin, buffer );
sscanf ( buffer.c_str(), "%d", &thisisanumber );
cout<<"You entered: "<<thisisanumber;
cin.get();
return 0;
}
And a more C++ish approach using stringstreams:
Code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int
main()
{
string buffer;
int thisisanumber;
cout<<"Please enter a number:";
getline ( cin, buffer );
istringstream iss ( buffer );
iss>> thisisanumber;
cout<<"You entered: "<<thisisanumber;
cin.get();
return 0;
}
-
Yup, works a treat. Thanks Prelude :)