Because there was an error in the code when I posted this question, it is not a good question. I have deleted and replaced it with a link to a correct solution.
Asked
Active
Viewed 799 times
-1
-
1As recommended you should check the length : http://stackoverflow.com/questions/7693484/is-this-the-correct-approach-to-do-input-validation-with-floating-point-values/7693538#7693538 of the buffer and input. – FailedDev Oct 09 '11 at 02:36
-
getline need buffer size. your code buffer size '\n' evaluate as integer – BLUEPIXY Oct 09 '11 at 10:50
2 Answers
1
The simplest fix here is to set a limit on your 'cin.getline()' call so it doesn't overflow your buffer, or alternatively switch over to using a string class or some such like so:
#include <iostream>
#include <errno.h>
int main() {
std::string buffer;
double value;
char* garbage = NULL;
while (true) {
std::cin >> buffer;
std::cout << "Read in: " << buffer << std::endl;
if (std::cin.good())
{
value = strtod(buffer.c_str(), &garbage);
if (errno == ERANGE)
{
std::cout << "A value outside the range of representable values was returned." << std::endl;
errno = 0;
}
else
{
std::cout << value << std::endl << garbage << std::endl;
if (*garbage == '\0')
std::cout << "good value" << std::endl;
else
std::cout << "bad value" << std::endl;
}
}
}
return 0;
}

Phil Street
- 2,735
- 2
- 20
- 25
1
cin.getline(buffer, '\n'); <-- is wrong, need buffer size.
cin.getline(buffer, 10000, '\n');

BLUEPIXY
- 39,699
- 7
- 33
- 70
-
Finally figured that out late last night before I passed out. I forgot about that parameter for c strings. with the getline member of the string class, you don't need to enter the size and I'm so used to using that. :) – Oct 09 '11 at 16:21