I'm using a function getProductCode to read a product code from the
keyboard. This function uses a return statement to send the product code to main.
My assignment is to Modify the program. I can not use return statement to send product code from getProductCode to main. Instead, I have to use pass-by-reference to achieve the same goal.
Every time I try to execute the code a window pops up that says "Lessons22Lab26P1.exe has stopped working; Windows can check online for a solution to the problem"
This only occurs when I enter a four digit number that ends in 4 or 7 however if I enter in any other value it will display what it is suppose to display "Invalid code. Please try again."
The following is my code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <cstdlib>
#include <iostream>
using namespace std;
string getProductCode(string &);
int main()
{
string productCode = "";
productCode = getProductCode(productCode);
cout << "Product code read from keyboard: " << productCode << endl;
system("pause");
return 0;
}
string getProductCode(string &productCode)
{
bool valid = false;
while (valid == false )
{
cout << "Enter the orange's 4-digit code. " << endl;
cout << "The last digit must be either 4 or 7." << endl;
cout << "Enter code here: ";
cin >> productCode;
if (productCode.length() == 4 && (productCode[3] == '4' || productCode[3] == '7'))
{
valid = true;
}
else
{
cout << "Invalid code. Please try again." << endl;
}
}
}
|
This was the original code given:
#include <cstdlib>
#include <iostream>
using namespace std;
string getProductCode();
int main()
{
string productCode = "";
productCode = getProductCode();
cout << "Product code read from keyboard: " << productCode << endl;
system("pause");
return 0;
}
string getProductCode()
{
string code = "";
bool valid = false;
while (valid == false )
{
cout << "Enter the orange's 4-digit code. " << endl;
cout << "The last digit must be either 4 or 7." << endl;
cout << "Enter code here: ";
cin >> code;
if (code.length() == 4 && (code[3] == '4' || code[3] == '7'))
{
valid = true;
}
else
{
cout << "Invalid code. Please try again." << endl;
}
}
return code;
}