Why is my vector initialisation making all objects in my array the same? - c++

I'm working on a program to aid me in world-building that randomly generates a settlement (hamlet, village, town, city) based on a nation (German, Latin, Eastern) that the user chooses. I've integrated a sort of settler generation system to create settlers within the settlement, each with a name, age, gender, and wealth using a constructor and holding the results as objects within a vector. Unfortunately, the program creates an entire population of clones, filling the vector with settlers with the same name, age, etc.
I've tried initialising the Settler class' constructor in a for loop, but that hasn't changed anything except causing you to get a different set of settlers each time you request information on one of them.
Settler Constructor:
class Settler {
public:
int settlerAge;
string settlerName;
string settlerGender;
string settlerWealth;
Settler(int type, int nation, int quantity) {
int result{};
string givenName{};
string surName{};
// Latin Male First Name
string latinMaleName[15] = {"Faustus", "Mamercus", "Mettius", "Appius", "Hostus", "Quintus", "Cossus", "Secundus", "Servius", "Gallio", "Tettienus", "Petronius", "Paesentius", "Pescunnius", "Clodius"};
// Latin Surname
string latinSurname[30] = {"Natalinus", "Lucilianus", "Crispian", "Laetinianus", "Falco", "Otho", "Plautius", "Pascentius", "Lepidus", "Moderatus", "Caeparius", "Caetronius", "Hostilius", "Aedinius", "Papius", "Gennadia", "Triaria", "Planta","Amantia", "Mico", "Opilio", "Augusta", "Laevina", "Longina", "Mico", "Servana", "Sicula", "Iovina", "Albana", "Concessa"};
// Latin Female First Name
string latinFemaleName[15] = {"Vorenia", "Tuccia", "Consentia", "Vinicia", "Aurelia", "Helvia", "Fabia", "Aemilia", "Petilia", "Cloelia", "Viducia", "Betiliena", "Sornatia", "Memmia", "Pedia"};
// As above, so below...
string germanMaleName[15] = {"Carsten", "Benedikt", "Emmerich", "Tillmann", "Maik", "Severin", "Adrian", "Gregor", "Ingolf", "Germund", "Adelmar", "Eckard", "Raimund", "Marwin", "Dietmar"};
string germanSurname[30] = {"Loeb", "Spielberg", "Lindemann", "Frenz", "Buxbaum", "Macher", "Bacharach", "Homrighausen", "Faulhaber", "Herder", "Germar", "Eisen", "Hackl", "Specht", "Rossmann", "Erdmann", "Osterhaus", "Steinsaltz", "Spiegelmann", "Lindemann", "Kluckhohn", "Kuttner", "Seelmann", "Sattler", "Kautner", "Dunhaupt", "Scharf", "Preisner", "Werthner", "Breitner"};
string germanFemaleName[15] = {"Selina", "Isabel", "Walburg", "Berta", "Kate", "Gisela", "Amelie", "Ronja", "Karin", "Lena", "Alexandra", "Sarah", "Monica", "Kai", "Nadja"};
// NOTE: Surname is before given name in eastern nations
string easternMaleName[15] = {"Nikki", "Moronobu", "Yaichiro", "Shuncho", "Tamasaburo", "Sekien", "Kazutoshi", "Yasuhide", "Omezo", "Kinzo", "Junji", "Utamuro", "Hisaki", "Taki", "Mitsuo"};
string easternSurname[30] = {"Maki", "Shinohara", "Tsukino", "Ikeda", "Matsutoya", "Sakata", "Horiuchi", "Suda", "Tsuga", "Kawano", "Kanbayashi", "Kirigaya", "Sakimoto", "Urushido", "Inaba", "Tsukiyomi", "Saeki", "Soga", "Morioka", "Yamabe", "Nakajima", "Maruyama", "Suga", "Kamino", "Kawamoto", "Takanashi", "Ito", "Kuramoto", "Maeda", "Kanemaru"};
string easternFemaleName[15] = {"Saito", "Ane", "Fuuko", "Taji", "Isoko", "Gen", "Kuwa", "Taira", "Sachi", "Uka", "Ryoko", "Hina", "Mitsu", "Asa", "Tomie"};
// Gender Generation (Male/Female)
result = (1 + (rand() % 2));
if (result > 1) {
settlerGender = "female";
} else {
settlerGender = "male";
}
// Name and Age Generation (See Arrays)
result = (rand() % 15);
switch(nation) {
case 1: // Latin (Equal split of ages)
if (settlerGender == "male") {
givenName = latinMaleName[result];
} else {
givenName = latinFemaleName[result];
}
result = (1 + (rand() % 100));
if (result >= 66) {
settlerAge = (41 + (rand() % 30));
} else if (result > 33 || result < 66) {
settlerAge = (22 + (rand() % 41));
} else {
settlerAge = (1 + (rand() % 22));
}
result = (rand() % 30);
surName = latinSurname[result];
settlerName = givenName + " " + surName;
break;
case 2: // German (More young people)
if (settlerGender == "male") {
givenName = germanMaleName[result];
} else {
givenName = germanFemaleName[result];
}
result = (1 + (rand() % 100));
if (result >= 90) {
settlerAge = (41 + (rand() % 30));
} else if (result > 40 || result < 90) {
settlerAge = (22 + (rand() % 41));
} else {
settlerAge = (1 + (rand() % 22));
}
result = (rand() % 30);
surName = germanSurname[result];
settlerName = givenName + " " + surName;
break;
case 3: // Eastern (More older people)
if (settlerGender == "male") {
givenName = easternMaleName[result];
} else {
givenName = easternFemaleName[result];
}
result = (1 + (rand() % 100));
if (result >= 40) {
settlerAge = (41 + (rand() % 30));
} else if (result > 20 || result < 40) {
settlerAge = (22 + (rand() % 41));
} else {
settlerAge = (1 + (rand() % 22));
}
result = (rand() % 30);
surName = easternSurname[result];
settlerName = surName + " " + givenName;
break;
}
// Wealth Generation (Poor/Decent/Rich: Based on Surname)
switch(type){
case 1: // Hamlet
if (result >= 28) {
settlerWealth = "Rich";
} else if (result > 24 || result < 28) {
settlerWealth = "Decent";
} else {
settlerWealth = "Poor";
}
break;
case 2: // Village
if (result >= 26) {
settlerWealth = "Rich";
} else if (result > 19 || result < 26) {
settlerWealth = "Decent";
} else {
settlerWealth = "Poor";
}
break;
case 3: // Town
if (result >= 25) {
settlerWealth = "Rich";
} else if (result > 9 || result < 25) {
settlerWealth = "Decent";
} else {
settlerWealth = "Poor";
}
break;
case 4: // City
if (result >= 20) {
settlerWealth = "Rich";
} else if (result > 9 || result < 20) {
settlerWealth = "Decent";
} else {
settlerWealth = "Poor";
}
break;
}
}
};
Vector Initialisation and Output:
Settlement objSettlement(tempType,tempNation);
int tempNum = objSettlement.settlementQuantity;
std::vector<Settler> objSettler(objSettlement.settlementQuantity, Settler(tempType, tempNation, tempNum));
cout << "Welcome to the " << objSettlement.settlementType << " " << objSettlement.settlementName << " in the " << objSettlement.settlementNation << " nation!\n";
cout << "Featuring a population of " << objSettlement.settlementQuantity << " with " << objSettlement.settlementWealth << " wealth.\n\n";
bool repeat = true;
while (repeat == true) {
cout << "Enter the ID of a settler you would like to read about (from 0-" << (objSettlement.settlementQuantity - 1) << ", or enter 999999 to exit): ";
cin >> tempNum;
cout << "\n\n";
if (tempNum == 999999) {
repeat = false;
} else {
cout << objSettler[tempNum].settlerName << ", " << objSettler[tempNum].settlerGender << ", is " << objSettler[tempNum].settlerAge << " years old and has " << objSettler[tempNum].settlerWealth << " wealth.\n\n";
}
}
For context, "objSettlement" refers to a randomly generated Settlement instance and ".settlementQuantity" is an integer representing the settlement's population.
So, when I create a latin hamlet with 30 people, the program creates a vector with 30 cases of: "Faustus Crispian, male, is 41 years old and has Poor wealth." regardless of what number I put in from 0-29.
Why is my vector initialisation making all objects in my array the same?

This :
std::vector<Settler> objSettler(objSettlement.settlementQuantity, Settler(tempType, tempNation, tempNum));
creates a vector with objSettlement.settlementQuantity copies of the same object Settler(tempType, tempNation, tempNum).
Refer to this reference page for details on how the various vector constructors work.
Something like this might be closer to what you want :
std::vector<Settler> objSettler;
for (int i = 0; i < objSettlement.settlementQuantity; ++i) {
objSettler.emplace_back(tempType, tempNation, tempNum);
}

When you create your objSettler vector, you create one Settler randomly, which will get copied objSettlement.settlementQuantity times. In other words, your constructor is called only once and the instances in the vector are created from that one settler object using the default copy constructor.
See std::vector
For generating n random settlers, you might want to use std::generate_n and std::back_inserter:
std::vector<Settler> objSettler;
std::generate_n(std::back_inserter(objSettler),
objSettlement.settlementQuantity,
[&](){ return Settler(tempType, tempNation, tempNum); });

Related

C++ 6.0 code ignored after compile (Date Time calculator code)

This project I'm working on is forcing me to use Visual C++-6.0 and it seems like everytime I compile this code it causes errors in not only this segment of code but elsewhere that is unrelated to this portion.
Right now I am trying to calculate an expiration date that is 15 months from the date that would be given.
I've tried researching if this is a common issue after windows updates. I know 6.0 has been unsupported and phased out but its a "requirement" for this program. I swore it was working 2 months ago and since that point about 30 patches have been deployed to my Windows 10 device.
Currently in this snippit of code the date that is passed into the code is carried through unaltered. For example: Nov-01-2019 should become Feb-01-2021
void CalculateDates(int numIndex)
{
int tDay = 0, tMonth = 0, tYear = 0, exp_Months = 15;
char sTemp1[4], sTemp2[4], sTemp3[4], sTemp4[4], sDay[4], sYear[4], *p;
p = Database[numIndexCount].sIdentifier;
strncpy(Database[numIndexCount].sPreparedBy, Database[numIndexCount].sIdentifier, 3);
Database[numIndexCount].sPreparedBy[3] = 0;
strncpy(sTemp1, p + 3, 2);
sTemp1[2] = 0;
strncpy(sTemp2, p + 5, 2);
sTemp2[2] = 0;
strncpy(sTemp3, p + 7, 2);
sTemp3[2] = 0;
strcpy(sTemp4, "20");
SetDateMonth(sTemp1);
sprintf(Database[numIndex].sPreparedDate, "%s-%s-%s%s", sTemp2, sMonth1, sTemp4, sTemp3);
tDay = atoi(sTemp2);
tMonth = atoi(sTemp1);
tYear = atoi(sTemp3);
if (tMonth <= 9) {
if (tMonth == 9) {
tMonth = 12;
tYear++;
// cout << "Is the month printing right? ";
// cout<<tMonth;
// cout << "\n";
}
else {
tMonth = (tMonth + exp_Months) % 12;
tYear++;
//cout << "Is the month printing right? ";
//cout<<tMonth;
//cout << "\n";
}
}
if (tMonth == 4 || tMonth == 6 || tMonth == 9 || tMonth == 11) {
// cout << "This is reached";
// cout << "\n";
// cout << "The day value is: ";
// cout << tDay;
// cout << "\n";
if (tDay == 31)
{
tDay = 30;
}
}
if (tDay >= 29 && tMonth == 2 && tYear % 4 == 0) {
if (tYear % 100 != 0) {
tDay = 29;
}
else if (tYear % 100 == 0 && tYear % 400 == 0) {
tDay = 29;
}
}
else if (tYear % 4 != 0 && tMonth == 2) {
tDay = 28;
}
sprintf(sTemp1, "%i", tMonth);
if (tDay < 10) sprintf(sDay, "0%i", tDay);
else sprintf(sDay, "%i", tDay);
if (tYear < 10) sprintf(sYear, "0%i", tYear);
else sprintf(sYear, "%i", tYear);
SetDateMonth(sTemp1);
sprintf(Database[numIndex].sUseByDate, "%s-%s-%s%s", sDay, sMonth1, sTemp4, sYear);
sprintf(sUseByDate, "%s-%s-%s%s", sDay, sMonth1, sTemp4, sYear);
}
End results for the above for today were Nov-01-19 but should have been Feb-01-19

DiceSum - How to extend if/ if-else statement to reroll dice if dice sum is not a certain number

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main()
{
int n;
int win = 0;
int lose = 0;
int dice1;
int dice2;
int diceSum;
srand(time(0));
cout << "How many turns would you like? ";
cin >> n;
for (int i = 1; i <= n; i++)
{
dice1 = rand()%6 + 1;
dice2 = rand()%6 + 1;
diceSum = dice1 + dice2;
if((diceSum == 2) || (diceSum == 3) || (diceSum == 12)){
win++;
}
else if((diceSum == 7) || (diceSum == 11)){
lose++;
}
else{
}
}
cout << "No. of Wins: " << win << endl;
cout << "No. of Losses: " << lose << endl;
cout<< setprecision(4)<<fixed<<showpoint;
cout << "\nThe experimental probability of winning "<< (static_cast<float>(win)/n)*100 <<
"%.\n";
return 0;
}
My assignments states that "...can be shown analytically that the long term probability of winning the dice game you have programmed in PA 8-3 is .4929293. Extend that program you wrote to run a large number of turns and calculate the empirical (experimental) probability." My last assignment I had to make a program to roll two die and reveal the dice sum. If it was a 2, 3, or 12, I won; if it was a 7 or 11 it was a loss, otherwise it would repeat the roll. I was unable to repeat the roll, now for this assignment, I have to do the same thing.This is my output from my current code
I you want to not take into account the cases where the sum is not 2,3,12,7 or 11 you have lot of possibilities, for instance :
closer to your code do i -=1; in the empty else {}
for (int i = 1; i <= n; i++)
{
dice1 = rand()%6 + 1;
dice2 = rand()%6 + 1;
diceSum = dice1 + dice2;
if((diceSum == 2) || (diceSum == 3) || (diceSum == 12)){
win++;
}
else if((diceSum == 7) || (diceSum == 11)){
lose++;
}
else{
i -= 1;
}
}
or increment i only when you win or lose and remove i++ in the for()
for (int i = 1; i <= n;)
{
dice1 = rand()%6 + 1;
dice2 = rand()%6 + 1;
diceSum = dice1 + dice2;
if((diceSum == 2) || (diceSum == 3) || (diceSum == 12)){
win++;
i++;
}
else if((diceSum == 7) || (diceSum == 11)){
lose++;
i++;
}
}
or the variant
i = n;
for (;;)
{
dice1 = rand()%6 + 1;
dice2 = rand()%6 + 1;
diceSum = dice1 + dice2;
if((diceSum == 2) || (diceSum == 3) || (diceSum == 12)){
win++;
if (!--i)
break;
}
else if((diceSum == 7) || (diceSum == 11)){
lose++;
if (!--i)
break;
}
}
or remove all about i and replace your for by do { dice1 = ..... } while ((win + lose) != n); without having the last else branch
do {
dice1 = rand()%6 + 1;
dice2 = rand()%6 + 1;
diceSum = dice1 + dice2;
if((diceSum == 2) || (diceSum == 3) || (diceSum == 12)){
win++;
}
else if((diceSum == 7) || (diceSum == 11)){
lose++;
}
} while ((win + lose) != n);
or the variant
for (;;) {
dice1 = rand()%6 + 1;
dice2 = rand()%6 + 1;
diceSum = dice1 + dice2;
if((diceSum == 2) || (diceSum == 3) || (diceSum == 12)){
if ((++win + lose) == n)
break;
}
else if((diceSum == 7) || (diceSum == 11)){
if ((++lose + win) == n)
break;
}
}
Example of execution whatever the way :
pi#raspberrypi:/tmp $ ./a.out
How many turns would you like? 1000
No. of Wins: 336
No. of Losses: 664
The experimental probability of winning 33.6000%.
This result it normal even it seems opposite of the intuition because the possibilities to make these numbers are :
2 : 1+1
3 : 1+2 2+1
12 : 6+6
and
7: 1+6 6+1 2+5 5+2 3+4 4+3
11 : 5+6 6+5
so 4 possibilities to win ( 1/3/12 ) and 8 possibilities to lose ( 7/11 ), so the probability to lose if two times more than the probability to win
I encourage you to always check the input, replacing
cin >> n;
by something like
if (!(cin >> n)) {
cerr << "invalid number" << endl;
return -1;
}

Function using string produced from another function C++ [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I had written a function , which is supposed to analyze and use the data (string to be specific) produced from another function and calculate the percentage of chars and print out the results.
this function is of type int but the previous function is of type string. I was thinking of using pointers but I don't know if it's a valid conversion.
I also don't believe that putting a function in another function argument is valid.
here is an almost complete function
int percentages(string line)
{
int overalcount;
double Leu, Phe, Ile, STA, Val, Ser, Pro, Thr, Ala, Tyr, STO, His, Gln, Asn, Lys, Asp, Glu, Cys, Trp, Arg, Gly;
int percentage, percentage1, percentage2, percentage3, percentage4, percentage5, percentage6, percentage7;
int percentage8, percentage9, percentage10, percentage11, percentage12, percentage13, percentage14;
int percentage15, percentage16, percentage17, percentage18, percentage19, percentage20;
int i;
for (i = 0; i + 3 < line.length(); i += 3)
{
overalcount++;
if(line.substr(i, 3) == "Phe")
{
Phe++;
if(!Phe == 0)
{
percentage = (Phe / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Leu")
{
Leu++;
if(!Leu == 0)
{
percentage = (Leu / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Ile")
{
Ile++;
if(!Ile == 0)
{
percentage = (Ile / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "STA")
{
STA++;
if(!STA == 0)
{
percentage = (STA / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Val")
{
Val++;
if(!Val == 0)
{
percentage = (Val / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Ser")
{
Ser++;
if(!Ser == 0)
{
percentage = (Ser / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Pro")
{
Pro++;
if(!Pro == 0)
{
percentage = (Pro / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Thr")
{
Thr++;
if(!Thr == 0)
{
percentage = (Thr / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Ala")
{
Ala++;
if(!Ala == 0)
{
percentage = (Ala / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Tyr")
{
Tyr++;
if(!Tyr == 0)
{
percentage = (Tyr / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "STO")
{
STO++;
if(!STO == 0)
{
percentage = (STO / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "His")
{
His++;
if(!His == 0)
{
percentage = (His / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Gln")
{
Gln++;
if(!Gln == 0)
{
percentage = (Gln / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Asn")
{
Asn++;
if(!Asn == 0)
{
percentage = (Asn / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Lys")
{
Lys++;
if(!Lys == 0)
{
percentage = (Lys / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Asp")
{
Asp++;
if(!Asp == 0)
{
percentage = (Asp / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Glu")
{
Glu++;
if(!Glu == 0)
{
percentage = (Glu / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Cys")
{
Cys++;
if(!Cys == 0)
{
percentage = (Cys / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Trp")
{
Trp++;
if(!Trp == 0)
{
percentage = (Trp / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Arg")
{
Arg++;
if(!Arg == 0)
{
percentage = (Arg / overalcount) * 100;
}
}
else if(line.substr(i, 3) == "Gly")
{
Gly++;
if(!Gly == 0)
{
percentage = (Gly / overalcount) * 100;
}
}
}
if(!percentage == 0)
{
cout << "Percentage of Phe: " <<percentage <<endl;
}
if(!percentage1 == 0)
{
cout << "Percentage of Leu: " <<percentage1 <<endl;
}
if(!percentage2 == 0)
{
cout << "Percentage of Ile: " <<percentage2 <<endl;
}
if(!percentage3 == 0)
{
cout << "Percentage of STA: " <<percentage3 <<endl;
}
if(!percentage4 == 0)
{
cout << "Percentage of Val: " <<percentage4 <<endl;
}
if(!percentage5 == 0)
{
cout << "Percentage of Ser: " <<percentage5 <<endl;
}
if(!percentage6 == 0)
{
cout << "Percentage of Pro: " <<percentage6 <<endl;
}
if(!percentage7 == 0)
{
cout << "Percentage of Thr: " <<percentage7 <<endl;
}
if(!percentage8 == 0)
{
cout << "Percentage of Ala: " <<percentage8 <<endl;
}
if(!percentage9 == 0)
{
cout << "Percentage of Tyr: " <<percentage9 <<endl;
}
return 0;
}
the argument "string line" is supposedly the string produced by the previous function. But it is instead recognizing the line that is read from the input filestream.
Here, take this much less gross function:
int percentages(string line)
{
map<string, int> words;
double count = line.length() / 3;
for (int i = 0; i + 3 < line.length(); i += 3)
++words[line.substr(i, 3)];
string find[10] = {"Phe", "Leu", "Ile", "STA", "Val", "Ser", "Pro", "Thr", "Ala", "Tyr"};
for (int i = 0; i < 10; ++i)
cout << "Percentage of " << find[i] << ": " << words[find[i]] / count << endl;
return 0;
}

Not sure why code is count twice [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
im not sure why the code for the variable known. its always doubling 2 times. the code is suppose to display the times processed valid card invalid cards and unknown cards. the known cards are the ones that are american express discover visa and master. im trying to get the count of them but it seems like they are always doubling for some reason
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void validateCC(string);
string checkCC(string, int, bool&);
bool validateCCNum(string);
string setCCType(string);
int proc = 0, valid = 0 , invalid = 0 , unknown = 0 , known = 0;
void main() {
string cardnum[300];
int ccLen;
ifstream openfile("Sample Credit Card numbers.txt");
if (openfile.is_open())
{
while(!openfile.eof())
{
for (int count = 0; !openfile.eof(); count++)
{
getline(openfile,cardnum[count]);
ccLen = cardnum[count].length();
cout<<"sdfsd";
proc++;
if (ccLen !=0)
{
validateCC(cardnum[count]);
}
}
}
cout<<valid<<" valid\n";
cout<<invalid<<" invalid\n";
cout<<unknown<< " unknwon\n";
cout<<proc<<" processed\n";
system("Pause");
}
}
void validateCC(string ccn) {
string msg;
bool OK;
int ccLen;
ccLen = ccn.length();
msg = checkCC(ccn, ccLen, OK);
if(!OK)
{
cout <<ccn<< msg << "\n";
invalid++;
}
else
{
if(validateCCNum(ccn))
{
msg = setCCType(ccn);
setCCType(ccn);
valid++;
cout<<ccn<<msg << "Card Type\n";
}
else
{
cout << (ccn)<<" Invalid"<< " credit card number\n";
invalid++;
}
}
}
string checkCC(string c, int cLen, bool& ccOK) {
string s = "";
ccOK = true;
for(int i=0;i<cLen && ccOK;++i)
ccOK = isdigit(c[i]);
if(ccOK == false) {
s = " Invalid credit card number digits";
} else if(cLen == 15) {
if(c.substr(0, 2) != "34" && c.substr(0, 2) != "37") {
ccOK = false;
s = " Invalid American Express credit card number";
}
} else if(cLen != 16) {
ccOK = false;
s = " Invalid credit card number length";
}
return s;
}
bool validateCCNum(string cc) {
bool flip = true;
int tmp, num = 0, ccLen = cc.length()-1;
for(int ndx=ccLen;ndx>=0;ndx--) {
if (flip)
num += cc[ndx] - '0';
else {
tmp = (cc[ndx] - '0') * 2;
if(tmp <= 9)
num += tmp;
else
num += (1 + (tmp - 10)); // max of 18
}
flip = !flip;
}
return num % 10 == 0;
}
string setCCType(string cc) {
int num = cc[0]-'0';
int num1 =cc[1]-'0';
int num2 = cc[2]-'0';
int num3 = cc[3]-'0';
string cct = " Unknown";
if(cc.length()==15 &&num ==3 &&num1 ==4|| cc.length()==15 &&num ==3 &&num1 ==7)
{
cct = " American Express";
known++;
}
else if(num == '4')
{
cct = " Visa";
known++;
}
else if(num ==5 && num1 ==1 ||num ==5 && num1 ==2|| num ==5 && num1 ==3||num ==5 && num1 ==4|| num ==5 && num1 ==5)
{
cct = " MasterCard";
known++;
}
else if (num == 6 && num1 ==0 && num2 == 1 && num3==1 || num ==6 && num==5)
{
cct = " Discover"; //ignoring other prefixes
known++;
}
else
{
unknown++;
}
return cct;
}
msg = setCCType(ccn);
setCCType(ccn);
You are calling the function twice. This counts the known/unknown twice.

I keep getting a 'no match for call to' error

#include <iostream>
#include <string>
using namespace std;
// Turns a digit between 1 and 9 into its english name
// Turn a number into its english name
string int_name(int n)
{
string digit_name;
{
if (n == 1) return "one";
else if (n == 2) return "two";
else if (n == 3) return "three";
else if (n == 4) return "four";
else if (n == 5) return "five";
else if (n == 6) return "six";
else if (n == 7) return "seven";
else if (n == 8) return "eight";
else if (n == 9) return "nine";
return "";
}
string teen_name;
{
if (n == 10) return "ten";
else if (n == 11) return "eleven";
else if (n == 12) return "twelve";
else if (n == 13) return "thirteen";
else if (n == 14) return "fourteen";
else if (n == 14) return "fourteen";
else if (n == 15) return "fifteen";
else if (n == 16) return "sixteen";
else if (n == 17) return "seventeen";
else if (n == 18) return "eighteen";
else if (n == 19) return "nineteen";
return "";
}
string tens_name;
{
if (n == 2) return "twenty";
else if (n == 3) return "thirty";
else if (n == 4) return "forty";
else if (n == 5) return "fifty";
else if (n == 6) return "sixty";
else if (n == 7) return "seventy";
else if (n == 8) return "eighty";
else if (n == 9) return "ninety";
return "";
}
int c = n; // the part that still needs to be converted
string r; // the return value
if (c >= 1000)
{
r = int_name(c / 1000) + " thousand";
c = c % 1000;
}
if (c >= 100)
{
r = r + " " + digit_name(c / 100) + " hundred";
c = c % 100;
}
if (c >= 20)
{
r = r + " " + tens_name(c /10);
c = c % 10;
}
if (c >= 10)
{
r = r + " " + teen_name(c);
c = 0;
}
if (c > 0)
r = r + " " + digit_name(c);
return r;
}
int main()
{
int n;
cout << endl << endl;
cout << "Please enter a positive integer: ";
cin >> n;
cout << endl;
cout << int_name(n);
cout << endl << endl;
return 0;
}
I Keep getting this Error code:
intname2.cpp: In function âstd::string
int_name(int)â:
intname2.cpp:74: error: no match for
call to â(std::string) (int)â
intname2.cpp:80: error: no match for
call to â(std::string) (int)â
intname2.cpp:86: error: no match for
call to â(std::string) (int&)â
intname2.cpp:91: error: no match for
call to â(std::string) (int&)â
You are using digit_name, teen_name, etc as functions, when they are defined as variables. If you want to use them like that, you need to define them before your int_name function like this:
string digit_name(int n)
{
if (n == 1) return "one";
else if (n == 2) return "two";
else if (n == 3) return "three";
else if (n == 4) return "four";
else if (n == 5) return "five";
else if (n == 6) return "six";
else if (n == 7) return "seven";
else if (n == 8) return "eight";
else if (n == 9) return "nine";
return "";
}
Timothy, it looks like you're confused about the requirements of the assignment. Please make sure you understand the requirements, because at this stage it doesn't look like you know what's expected of you. You're trying to move the body of one function into the body of another function and that's simply not possible to do.
Please post the exact words that your teacher used in order for us to give you proper advice on the question.
Here are some tips for you:
If your teacher has covered switch statements then use switch statements.
Check if your teacher is not asking you to do function declarations.
Check if your teacher is not asking you to put the functions in libraries (a header file and source file).
OK scrap the tips... given your teacher's requirements I think it might look a little bit like this:
string int_name(int n)
{
int c = n; // the part that still needs to be converted
string r; // the return value
if (c >= 1000)
{
r = int_name(c / 1000) + " thousand";
c = c % 1000;
}
if (c >= 100)
{
// If you have covered switch statements then it will look like this
string digitName;
switch(c/100) // <- instead of calling digit_name(c/100), we call switch(c/100)
{
case 1:
// assign the digit name
digitName = "one";
break;
case 2:
//... fill here with your own code
break;
case 3:
//... fill here with your own code
break;
// write all the cases through 9
default:
digitName = "";
break;
}
// in the result string use the digitName variable
// instead of calling the digit_name function
r = r + " " + digitName + " hundred";
c = c % 100;
}
if (c >= 20)
{
r = r + " " + tens_name(c /10);
c = c % 10;
}
if (c >= 10)
{
r = r + " " + teen_name(c);
c = 0;
}
if (c > 0)
r = r + " " + digit_name(c);
return r;
}
Note that I'm using a switch statement, but if you your teacher hasn't shown you switch statements yet, then you can still use if/else statements:
string int_name(int n)
{
int c = n; // the part that still needs to be converted
string r; // the return value
if (c >= 1000)
{
r = int_name(c / 1000) + " thousand";
c = c % 1000;
}
if (c >= 100)
{
// declare a digitName
string digitName;
// declare a temporary value
int temp = c/100;
if(1 == temp)
{
// assign the digit name
digitName = "one";
}
else if( 2 == temp )
{
digitName = "two";
}
else if( 3 == temp )
{
// fill in the rest
}
else if( 4 == temp )
{
// fill in the rest
}
// write all the other else if statements
else
{
digitName = "":
}
// in the result string use the digitName variable
// instead of calling the digit_name function
r = r + " " + digitName + " hundred";
c = c % 100;
}
if (c >= 20)
{
r = r + " " + tens_name(c /10);
c = c % 10;
}
if (c >= 10)
{
r = r + " " + teen_name(c);
c = 0;
}
if (c > 0)
r = r + " " + digit_name(c);
return r;
}
You're going to have to take the first example with digit_name and apply it to tens_name and teen_name functions.
WARNING:
In reality you don't want to repeat the same code and clutter a single function with a bunch of code that could be in its own function. You ALWAYS want to break out repeating code into functions... if she's asking you to repeat code when you can use functions then you should be concerned. Ask your teacher if this is what she REALLY wants you to do!