Getline vs Get Problems, and Input Buffer Confusion
Hi all,
I recently started learning C++, and have been using the following book:
C++ Without Fear: A Beginner's Guide That Makes You Feel Smart
I'm also using Microsoft Visual C++ Express 2010, if it matters.
It's very approachable, and so far I've gotten a lot out of it. I'm currently doing an exercise with strings and it cautions against buffer overflow, but simply suggests making inordinately large char arrays to catch potential problems. This seems like a terrible solution, so I started digging for a better answer.
The best I've found is using the cin.get() function along with cin.sync(). Here's the code I'm using:
Code:
#define STRLENMAX 4
#include <iostream>
#include <string.h>
#include <math.h>
#include <stdlib.h>
using namespace std;
int get_number();
int main() {
int x;
for (;;) {
cout << "Enter a number (press ENTER to exit): ";
x = get_number();
if (x == 0)
break;
cout << "The square root of x is: " << sqrt(double(x)) << endl;
}
return 0;
}
int get_number() {
char s[STRLENMAX];
cin.get(s, STRLENMAX - 1);
cin.sync();
if (strlen(s) == 0)
return 0;
return atoi(s);
}
This seems to work fine, but there are a few issues I need some clarification on:
- If I change the cin.get to a cin.getline function, the program no longer works as expected. The example I saw used the getline function just fine, but it doesn't work here - instead it appears to not be flushing the input buffer as expected when entering a large number. Can anyone explain why this is?
For example, using the .get function, if I type a 3 digit number, the square root of the first 2 digits is returned appropriately, the remaining input is dropped, and I can continue using the program just fine. Using the .getline function, if I type a 3 digit number, the square root of the first 2 digits is returned appropriately, but the program ends (as if I had hit enter with no input). Based on the descriptions here and here, the reverse should be happening, since getline should be dropping the \n delimiter. - I'm defining the STRLENMAX constant as 4, so I would expect I should be able to process a 3 digit number (since I read STRLENMAX - 1 (3), plus the null byte). From my testing, I can only process 2 digit numbers. Why is this?
- This may all be unneccessary, but I was trying to find the 'ideal' way to read input from the console, and this was the best I could come up with. Is there a better, easier, more efficient way?
Thanks in advance!