![]() |
| | #1 |
| Registered User Join Date: Apr 2004
Posts: 14
| Compiler Problem 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;
}
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 |
| sitestem is offline | |
| | #2 |
| Code Goddess Join Date: Sep 2001
Posts: 9,661
| 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;
}
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;
}
__________________ My best code is written with the delete key. |
| Prelude is offline | |
| | #3 |
| Registered User Join Date: Apr 2004
Posts: 14
| Yup, works a treat. Thanks Prelude |
| sitestem is offline | |
![]() |
| Thread Tools | |
| Display Modes | |
|
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Compiler problem | xixpsychoxix | C++ Programming | 5 | 01-17-2009 12:46 PM |
| Dev-C++ compiler problem | GrasshopperEsq | C++ Programming | 19 | 05-08-2008 02:35 AM |
| C / OpenGL help REALLY needed for simple but annoying problem! | Oz_joker | C Programming | 5 | 12-03-2003 05:47 PM |
| Problem with compiler | knight543 | C++ Programming | 4 | 02-09-2002 09:16 PM |
| Please help me with this compiler problem | incognito | C++ Programming | 1 | 01-05-2002 05:14 PM |