I have just started to code in c++ this year, so I am by no means an expert. For an assignment from my teacher I was given the assignment to create a Safe Data Entry program that would (using some given code, and ours added) force a user to enter a proper value (whether double or integral). I created the code for this and most of it seemed to make logical sense to me and my associates the only issue is, it doesn't work. We have checked it over (More than two people), and have found nothing wrong. Code is here in a google doc, so I could post it quicker.
At a glance, you used = where you should have used ==. Also, the do-while condition in the getDouble function can never be true. Is there a reason you're testing first character of the strings for every index into the string (and why is that part of an if/else chain?)
#include <iostream>
#include <iomanip>
#include <string>
#include <cctype>
#include <cstdlib>
usingnamespace std;
int getInt( void ); //returns viable int
double getDouble( void ); //returns viable double
int main()
{
int intTest = -9999;
double doubleTest = -999.999;
cout << " Welcome to Safe Data Entry!\n===============================" << endl;
intTest = getInt();
cout << "You have successfully entered an integer, " << intTest << endl;
cout << intTest << " + 5 = " << intTest + 5 << endl; //proves an int
/*
doubleTest = getDouble();
cout << "You have successfully entered an double " << doubleTest << endl;
cout << doubleTest << " + 10.123 = " << doubleTest + 10.123 << endl;
*/
cout << endl;
system("pause");
return EXIT_SUCCESS;
}
/*
int getInt(void) gets data from the user, stores it in a string
tests the string to ensure the value entered is an int(positive or negative),
then converts the string to an int to be returned to the main().
*/
int getInt( void )
{
string str = ""; int a = 1, d = 1;
while(a = 1)
{
a = 0;
cout << "Please enter a Integer ";
cin >> str;
cout << endl;
for(int i = 0; i < str.size(); i++)
{
if(isdigit(str[i]))
{
//no effect
}
elseif(str[0] == '-')
{
//no effect
}
else
{
a = 1;
}
}
}
int b = atoi( str.c_str() );
return b;
}
/*
double getDouble(void) gets data from the user, stores it in a string
tests the string to ensure that the value entered is a double ( maybe even
checking for only 0 or 1 decimals and positive or negative),then converts the
string to an double to be returned to the main().
*/
double getDouble( void )
{
string str, str2; int a = 1, b = 0;
do{
cout << "Please enter a Double ";
cin >> str;
cout << endl << endl;
for(int i = 0; i < str.size(); i++)
{
if(str[0] == '-')
{
a = a*-1;
}
elseif(isdigit(str[i]))
{
str2 += str[i];
}
}
}while(a == 0);
return 0;
}