Reputation: 19
I have been trying to get this correct for a while now. I finally gave up, I need help. So, what I'm trying to do is to get the user to provide me with valid double input with only one decimal point, e.g - "12.1". If a user enters 12.1.1 I want the program to start all over again till a valid double input is provided.
Thanks!
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
double ReadDouble(string prompt);
int main() {
ReadDouble("Enter double: \n");
}
double ReadDouble(string prompt) {
string input;
bool done = false;
do {
cout << prompt;
cin >> input;
done = true;
for (int i = 0; i < input.length(); i++) {
int count = 0;
if (isdigit(input[i]) == 0) {
if (ispunct(input[i]) != 0) {
count++;
count > 1 ? done = false : done = true;
} else {
done = false;
}
}
}
} while (done == false);
double retVal = stod(input.c_str());
cout << retVal << endl;
return retVal;
}
Upvotes: 0
Views: 1086
Reputation: 3573
I know you want to manually parse the user's input yourself, but using a regex simplifies the process. This matches any number of digits, optionally a period, then another optional digit.
#include <iostream>
#include <string>
#include <regex>
bool ValidateDouble(const std::string& str) {
const std::basic_regex dbl (R"(^\d+\.?\d?$)");
return std::regex_match(str, dbl);
}
double ReadDouble(const std::string& prompt) {
std::string input;
bool match = false;
do {
std::cout << prompt;
std::getline(std::cin, input);
match = ValidateDouble(input);
} while (!match);
return std::stod(input);
}
int main() {
double d = ReadDouble("Enter double: ");
std::cout << d << '\n';
}
Upvotes: 2
Reputation: 161
made some minor changes in your code, maybe it can meet your requirements. Here is the code:
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
double ReadDouble(string prompt);
int main() {
ReadDouble("Enter double: \n");
}
double ReadDouble(string prompt) {
string input;
bool done = false;
do {
cout << prompt;
cin >> input;
done = false;
int count = 0;
for (int i = 0; i < input.length(); i++) {
if (isdigit(input[i]) == 0) {
if (ispunct(input[i]) != 0) {
count++;
continue;
}
else
{
count++;
break;
}
}
else
continue;
}
count > 1 ? done = false : done = true;
} while (done == false);
double retVal = stod(input.c_str());
cout << retVal << endl;
return retVal;
}
If enter "12.1.1" and the program will ask you to reinput the double until the correct double entered, maybe like this:
Enter double:
12.1.1
Enter double:
12.1.33
Enter double:
12.1
12.1
press any key to continue. . .
Upvotes: 0