Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I need some help with this program I am writing in class. When ever I get ready to compile it it gives me an error that there are multiple definitions and i have tried to figure out what the mistake is but i cant. your help would be be helpful and thanks in advance.
It seems that the problem is with main.cpp, person.h, and person.cpp.
main.cpp
#include <iostream>
#include "person.cpp"
using namespace std;
int main(int argc, char *argv[])
{
Person p1;
p1.setFirstName("Carlos");
p1.setLastName("Martinez");
p1.setMiddleInit('X');
p1.setStreetAddress("Avenue");
p1.setCity("Atlanta");
p1.setState("GA");
p1.setZipCode("568467");
p1.setHomePhone("829385925");
p1.setWorkPhone("990128399");
cout << p1.getFirstName() << endl;
cout << p1.getLastName() << endl;
cout << p1.getMiddleInit() << endl;
cout << p1.getStreetAddress() << endl;
cout << p1.getCity() << endl;
cout << p1.getState() << endl;
cout << p1.getZipCode()<< endl;
cout << p1.getHomePhone() << endl;
cout << p1.getWorkPhone() << endl;
//system("PAUSE"); // only needed for devc++
return 0;
}
person.h
#include "date.h"
#ifndef PERSON_H
#define PERSON_H
class Person {
public:
Person();
~Person();
Date dateOfBirth;
void setLastName(char*);
void setFirstName(char*);
void setMiddleInit(char);
void setStreetAddress(char*);
void setCity(char*);
void setState(char*);
void setZipCode(char*);
void setHomePhone(char*);
void setWorkPhone(char*);
char* getLastName();
char* getFirstName();
char getMiddleInit();
char* getStreetAddress();
char* getCity();
char* getState();
char* getZipCode();
char* getHomePhone();
char* getWorkPhone();
private:
char lastName[21];
char firstName[16];
char middleInit;
char streetAddress[26];
char city[21];
char state[3];
char zipcode[11];
char homePhone[13];
char workPhone[13];
};
#endif
person.cpp
#include <string.h>
#include "person.h"
Person::Person(){}
Person::~Person(){}
void Person::setLastName(char *s)
{
strcpy(lastName,s);
}
char* Person::getLastName()
{
static char temp[21];
strcpy(temp,lastName);
return temp;
}
void Person::setFirstName(char *s)
{
strcpy (firstName,s);
}
char* Person::getFirstName()
{
static char temp[16];
strcpy (temp,firstName);
return temp;
}
void Person::setMiddleInit(char s)
{
middleInit = s;
}
char Person::getMiddleInit()
{
return middleInit;
}
void Person::setStreetAddress(char *s)
{
strcpy(streetAddress,s);
}
char* Person::getStreetAddress()
{
static char temp[26];
strcpy (temp, streetAddress); // street is copied to temp which is returned
return temp;
}
void Person::setCity(char *s)
{
strcpy(city,s);
}
char* Person::getCity()
{
static char temp[21];
strcpy (temp, city); // city is copied to temp which is returned
return temp;
}
void Person::setState(char *s)
{
strcpy(state,s);
}
char* Person::getState()
{
static char temp[3];
strcpy (temp, state); // state is copied to temp which is returned
return temp;
}
void Person::setZipCode(char *s)
{
strcpy(zipcode,s);
}
char* Person::getZipCode()
{
static char temp[11];
strcpy (temp, zipcode); // zipcode is copied to temp which is returned
return temp;
}
void Person::setHomePhone(char *s)
{
strcpy(homePhone,s);
}
char* Person::getHomePhone()
{
static char temp[13];
strcpy (temp, homePhone); // homephone is copied to temp which is returned
return temp;
}
void Person::setWorkPhone(char *s)
{
strcpy(workPhone,s);
}
char* Person::getWorkPhone()
{
static char temp[13];
strcpy (temp, workPhone); // work phone is copied to temp which is returned
return temp;
}
I also have a date.h and date.cpp but that does not seem to be the problem.
date.h
#ifndef DATE_H
#define DATE_H
class Date {
public:
Date();
~Date();
void setDate( int, int, int );
int getDay(); // method or function to retrieve a day value
int getMonth(); // method or function to retrieve a month value
int getYear(); // method or function to retrieve a year value
private:
int day; // data member of this class
int month; // data member of this class
int year; // data member of this class
};
#endif
date.cpp
#include <iostream>
#include <string>
#include "date.h"
using namespace std;
Date::Date(){
day = 1; // this and the following lines insure that Date objects
month = 1; // start in a consistent state
year = 1900;
}
// the following destructor releases resources used by objects of type Date
// when they no longer exist
Date::~Date()
{
}
void Date::setDate( int d, int m, int y )
{
if ( y >= 1900 )
year = y; // validates that year is 1900 or greater
else{
year = 1900;
cout << "Invalid year! " << y << endl;
}
if ( m >= 1 && m <= 12)
month = m;
else{
month = 1;
day = 1;
cout << "Invalid month!" << endl;}
if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12)
{
if ( d >= 1 && d <= 31 )
day = d;
else {
day = 1;
cout << "Invalid day! " << d << endl;
}
}
else { if ( m == 4 || m == 6 || m == 9 || m == 11 )
{
if ( d >= 1 && d <= 30 )
day = d;
else
{
day = 1;
cout << "Invalid day! " << d << endl;
}
}
else
{
if ( m = 2 )
{
if ( y % 4 == 0 && y % 400 != 0 )
{
if ( d >= 1 && d <= 29 )
day = d;
else
{
day = 1;
cout << "Invalid day! " << d << endl;
}
}
else
{
if ( d >= 1 && d <= 28 )
day = d;
else
{
day = 1;
cout << "Invalid day! " << d << endl;
}
}
}
}
}
} // end of functionint
Date::getDay()
{
int temp;
temp = day;
return temp;}
int Date::getMonth()
{
int temp;
temp = month;
return temp;
}
int Date::getYear()
{ int temp;
temp = year;
return temp;
}
here are the errors
In main.cpp, change "person.cpp" to "person.h", as Mike Kinghan said.
Also, in person.h, you should include the date.h file after the header guard:
#ifndef PERSON_H
#define PERSON_H
#include "date.h"
...
#endif
Related
Aim is to make sure that the user entered input for string 1 and string 2 contains only characters A,T,G or C in any order. If either string contains another other character then error should be displayed. Example:
Input contains error
Error in String #1: aacgttcOgMa
Error in String #2: ggataccaSat
This is my attempt at LCS.cpp file code:
#include "LCS.h"
#include <string>
using namespace std;
bool validate(string strX, string strY)
{
string x = strX;
string y = strY;
char searchItem = 'A';
char searchItem = 'C';
char searchItem = 'G';
char searchItem = 'T';
int numOfChar = 0;
int m = strX.length();
int n = strY.length();
for (int i = 0; i < m; i++)
{
if (x[i] == searchItem)
{
numOfChar++;
}
for (int i = 0; i < n; i++)
{
if (y[i] == searchItem)
{
numOfChar++;
}
}
}
This is my LCS.h file code:
#pragma once
#ifndef LCS_H
#define LCS_H
#include <string>
using namespace std;
bool validate(string strX, string strY);
#endif
And my driver file "Driver6.cpp" has this code:
#include "LCS.h"
#include <iostream>
#include <string>
using namespace std;
int main()
{
string strX, strY;
cout << "String #1: ";
cin >> strX;
cout << "String #2: ";
cin >> strY;
//validate the input two strings
if (validate(strX, strY) == false)
{
return 0;
}
int m = strX.length();
int n = strY.length();
}
Didn't really want to do this but it seems like the best bet rather than going round the houses in the comments:
#include <string>
#include <iostream>
bool validate( const std::string & s ) {
for ( auto c : s ) {
if ( c != 'A' && c != 'T' && c != 'C' && c != 'G' ) {
return false;
}
}
return true;
}
int main() {
std::string s1 = "ATGCCCG";
std::string s2 = "ATGfooCCCG";
if ( validate( s1 ) ) {
std::cout << "s1 is valid\n";
}
else {
std::cout << "s1 is not valid\n";
}
if ( validate( s2 ) ) {
std::cout << "s2 is valid\n";
}
else {
std::cout << "s2 is not valid\n";
}
}
Another technique:
bool validate(const std::string& s)
{
const static std::string valid_letters("ATCGatcg");
for (auto c: s)
{
std::string::size_type position = valid_letters.find_first_of(c);
if (position == std::string::npos)
{
return false;
}
}
return true;
}
The above code searches a container of valid letters.
I have problem when i try to change my 2 private class variables in FBullCowGame.h .It seems like constructor is calling function Reset() [Located in FBullCowGame.cpp] but Reset() function wont change integers MyMaxTries & MyCurrentTry.I'm new to c++ so probably it's something obvious but i can't find it .
This is main.cpp
#include <iostream>
#include <string>
#include "FBullCowGame.h"
using FText = std::string;
void PrintIntro();
void PlayGame();
FText GetGuess();
FText PrintGuess();
FBullCowGame BCGame;//Dodeljujemo naziv u main-u FBullCowGame-u , takodje ako ima neki kod u constructoru on ga izvrsava pri ovaj deklaraciji
bool AskToPlayAgain();
int main()
{
bool bPlayAgain = false;
do {
PrintIntro();
PlayGame();
bPlayAgain = AskToPlayAgain();
}
while (bPlayAgain);
return 0;
}
void PrintIntro()
{
//Define constant var
constexpr int WORD_LENGHT = 6;
//Welcome to the player and asking the guess
std::cout << "Welcome to Bulls and Cows\n";
std::cout << "Can you guess my " << WORD_LENGHT;
std::cout << " letter isogram word?\n";
}
void PlayGame()
{
BCGame.Reset();
int MaxTries = BCGame.GetMaxTries();
//Looping for guesses
for (int i = 1; i <= MaxTries; i++)
{
FText Guess = GetGuess();
//Repeat the guess back to them
std::cout << "Your guess is: " << Guess << std::endl;
std::cout << std::endl;
}
return;
}
FText GetGuess()
{
int CurrentTry = BCGame.GetCurrentTry();
//Player enters their guess
std::cout << std::endl << "Try " << CurrentTry << ".What is your guess?\n";
FText Guess = "";
std::getline(std::cin, Guess);
return Guess;
}
bool AskToPlayAgain()
{
FText Response = "";
std::cout << "Do you want to play again (y/n) ?" << std::endl;
std::getline(std::cin, Response);
return (Response[0] == 'y') || (Response[0] == 'Y');
}
FBullCowGame.h /
#pragma once
#include <string>
class FBullCowGame {
public:
FBullCowGame();//Constructor izvrsava se kod u njemu pri deklaraciji BCGame u nasem slucaju
int GetMaxTries() const;
int GetCurrentTry()const;
bool IsGameWon()const;
void Reset();
bool CheckGuessValidity(std::string);
private:
//Compile time values gets overwritten by run time values in Constructor
int MyMaxTries;
int MyCurrentTry;
};
And FBullCowGame.cpp /
#include "FBullCowGame.h"
FBullCowGame::FBullCowGame()
{
//Run time values
Reset();
}
void FBullCowGame::Reset()
{
constexpr int MAX_TRIES = 8;
int MyMaxTries = MAX_TRIES;
int MyCurrentTry = 1;
return;
}
int FBullCowGame::GetMaxTries ()const
{
return MyMaxTries;
}
int FBullCowGame::GetCurrentTry ()const
{
return MyCurrentTry;
}
bool FBullCowGame::IsGameWon ()const
{
return false;
}
bool FBullCowGame::CheckGuessValidity(std::string)
{
return false;
}
You are shadowing your member variables with function-local variables that happen to have the exact same name.
void FBullCowGame::Reset()
{
constexpr int MAX_TRIES = 8;
int MyMaxTries = MAX_TRIES;
int MyCurrentTry = 1;
return;
}
Just assign to your member variables, but don't redeclare them
void FBullCowGame::Reset()
{
constexpr int MAX_TRIES = 8;
MyMaxTries = MAX_TRIES;
MyCurrentTry = 1;
}
in below there is the Header File for dateType.
h class. after debug it showing in consul windows this :
Consul Image
Header File : dateType.h
#ifndef dateType_H
#define dateType_H
class dateType
{
public:
void setDate(int, int, int);
void setMonth(int);
void setDay(int);
void setYear(int);
void print() const;
int numberOfDaysPassed();
int numberOfDaysLeft();
void incrementDate(int nDays);
int getMonth();
int getDay();
int getYear();
int getDaysInMonth();
bool isLeapYear();
dateType(int = 1, int = 1, int = 1900);
private:
int dMonth;
int dDay;
int dYear;
};
#endif
main() Function :
#include <iostream>
#include<time.h>
#include "dateType.h"
using namespace std;
int main ()
{
cout <<" Program work with data type"<<endl;
dateType myDate(1,1,1900);
cout << "\n\n The current Date is : "<<endl;
myDate.print();
cout <<endl;
cout <<"\n\n days in this year are :" <<endl;
myDate.getDaysInMonth();
cout <<endl;
cout <<"\n\n Days passed in this year are :"<<endl;
myDate.numberOfDaysPassed();
cout <<endl;
cout <<"\n\n Days remaining in this year are :"<<endl;
myDate.numberOfDaysLeft();
cout <<endl;
myDate.incrementDate(7);
cout <<"\n\n New date after adding days is "<<endl;
cout <<endl;
myDate.print();
cout <<endl;
system("pause");
return 0;
}
Implementation file .cpp :
#include <iostream>
#include "dateType.h"
using namespace std;
void dateType::setDate(int month,int day,int year)
{
setYear(year);
setMonth(month);
setDay(day);
}
void dateType::setMonth(int month)
{
if(month > 0 && month < 13)
dMonth =month;
else
dMonth = 1;
}
void dateType::setDay(int day)
{
int days[12]= {31,28,31,30,31,30,31,31,30,31,30,31};
if (isLeapYear())
days[1]++;
if(day >= 1 && day <=days [dMonth -1])
dDay =day;
else
dDay =1;
}
void dateType::setYear(int year)
{
if (((int)log10((double)year) + 1)!=4)
dYear = 1990;
else dYear = year;
}
int dateType::getDaysInMonth()
{
int days[12]= {31,28,31,30,31,30,31,31,30,31,30,31};
if (isLeapYear())
days[1]++;
return days[ dYear -1 ];
}
int dateType::numberOfDaysPassed()
{
int days[12]= {31,28,31,30,31,30,31,31,30,31,30,31};
int m, daysPassed;
if (isLeapYear())
days[1]++;
m = dYear-1;
daysPassed=0;
while(m>0)
{
daysPassed+= days[m-1];
m--;
}
daysPassed+= dDay;
return daysPassed;
}
int dateType::numberOfDaysLeft()
{
int daysRemaining=365;
if (isLeapYear())
daysRemaining++;
daysRemaining-= numberOfDaysPassed();
return daysRemaining;
}
void dateType::incrementDate(int nDays)
{
while ((nDays + dDay) > dateType::getDaysInMonth())
{
nDays -= dateType::getDaysInMonth();
if (dMonth == 12)
{
dMonth = 0;
dYear++;
}
dMonth++;
}
dDay += nDays;
}
int dateType::getDay()
{
return dDay;
}
int dateType::getMonth()
{
return dMonth;
}
int dateType::getYear()
{
return dYear;
}
void dateType::print() const
{
cout <<"\n\t"<<dMonth<<"-"<<dDay<<"-"<<dYear;
}
dateType::dateType(int month, int day, int year)
{
setDate(month,day,year);
}
bool dateType::isLeapYear()
{
if (dYear % 400 == 0 || ( dYear % 100 !=0 && dYear % 4 ==0))
return true;
else
return false;
}
I am not sure about calculating I thing i did wrong with these :
days in this year are :
Days passed in this year are :
Days remaining in this year are :
The functions getDaysInMonth, numberOfDaysPassed and numberOfDaysLeft don't print anything, they only return a value.
You have to print the value, so something like std::cout << myDate.getDaysInMonth() << '\n';
You print days in this year are :, but the function you call is getDaysInMonth. I don't know which one you need, but the logic is for both wrong.
If you need the days in the year, then you only need to return 365 or 366, depending if it is a leap year or not.
If you need the days in the month, you should decrement dMonth instead of dYear, as you want the month, and not the year (because you are currently use the year as index, you're accessing memory you don't own, which will result in an access violation exception or some random value).
The function numberOfDaysPassed calculates m as follows m = dYear - 1;, but again, you should be using dMonth. You should also consider using a for loop instead of a while:
for (int i = dMonth - 1; i > 0; --i)
daysPassed += days[i - 1];
I have included both my definition of the Question class and its implementation, the first is a header file and the second a cpp file.
I put comments in to show where the problem is. For some reason under the constructor I can cout the questionText just fine but when I try to do this under the getQuestionText function it just outputs an empty string? Any help would be most appreciated!! Thanks!
#include <string>
#include <vector>
#include <iostream>
using namespace std;
#ifndef QUESTION_H
#define QUESTION_H
class Question{
public:
Question(int thePointValue, int theChapterNumber, \
string theQuestionText);
int getPointValue() const;
int getChapterNumber() const;
string getQuestionText() const;
virtual void writeQuestion(ostream& outfile) const;
virtual void writeKey(ostream& outfile) const;
private:
int pointValue;
int chapterNumber;
string questionText;
void writePointValue(ostream& outfile) const;
};
#endif
#include "Question.h"
Question::Question(int thePointValue, int theChapterNumber, \
string theQuestionText)
{
pointValue = thePointValue;
chapterNumber = theChapterNumber;
questionText = theQuestionText;
//HERE THIS WORKS PERFECTLY
cout << questionText << endl;
}
int Question::getPointValue() const
{
return pointValue;
}
int Question::getChapterNumber() const
{
return chapterNumber;
}
string Question::getQuestionText() const
{
//THIS IS THE PROBLEM. HERE IT OUPUTS AN EMPTY STRING NO MATTER WHAT!
cout << questionText << endl;
return questionText;
}
void Question::writeQuestion(ostream& outfile) const
{
writePointValue(outfile);
outfile << questionText << endl;
}
void Question::writeKey(ostream& outfile) const
{
writePointValue(outfile);
outfile << endl;
}
void Question::writePointValue(ostream& outfile) const
{
string pt_noun;
if (pointValue == 1)
pt_noun = "point";
else
pt_noun = "points";
outfile << "(" << pointValue << " " << pt_noun << ") ";
}
vector<Question *> QuestionsList(string filename, int min, int max)
{
vector<Question *> QuestionList;
string line;
vector<string> text;
ifstream in_file;
in_file.open(filename.c_str());
while (getline(in_file, line))
{
text.push_back(line);
}
string type;
for(int i = 0; i < text.size(); i ++)
{
int num = text[i].find('#');
type = text[i].substr(0, num);
if (type == "multiple")
{
MultipleChoiceQuestion myq = matchup(text[i]);
MultipleChoiceQuestion* myptr = &myq;
if (myq.getChapterNumber() >= min && myq.getChapterNumber() <= max)
{
QuestionList.push_back(myptr);
}
}
if (type == "short")
{
ShortAnswerQuestion myq = SAmatchup(text[i]);
ShortAnswerQuestion* myptr = &myq;
if (myq.getChapterNumber() >= min && myq.getChapterNumber() <= max)
{
QuestionList.push_back(myptr);
}
}
if (type == "long")
{
LongAnswerQuestion myq = LAmatchup(text[i]);
LongAnswerQuestion* myptr = &myq;
if (myq.getChapterNumber() >= min && myq.getChapterNumber() <= max)
{
QuestionList.push_back(myptr);
}
}
if (type == "code")
{
CodeQuestion myq = CODEmatchup(text[i]);
CodeQuestion* myptr = &myq;
if (myq.getChapterNumber() >= min && myq.getChapterNumber() <= max)
{
QuestionList.push_back(myptr);
}
}
cout << QuestionList[QuestionList.size()-1]->getQuestionText() << endl;
}
for (int i = 0; i < QuestionList.size(); i ++)
{
int numm = QuestionList.size();
cout << QuestionList[numm-1]->getQuestionText() << endl;
}
return QuestionList;
}
then when i call this in main the code breaks
vector<Question *> list = QuestionsList(pool_filename, min_chapter, max_chapter);
cout << list[0]->getQuestionText() << endl;
You are declaring, multiple times in your code, local objects and storing their pointer into the QuestionList vector (returned by the function) which, at the end of the function block, will contains dangling pointers.
MultipleChoiceQuestion myq = matchup(text[i]); // < local object
MultipleChoiceQuestion* myptr = &myq; // < pointer to local object
QuestionList.push_back(myptr); // < push back into vector
At this point you can either use dynamic memory allocation (I suggest you not to do that unless you are absolutely forced, and even in that case use one of the smart pointers provided by the standard library) or store the objects directly inside the vector.
I find myself oddly perplexed on this homework assignment. The idea is to create a Palindrome program, using a specific header the professor wants us to use, but for some reason, when I run it, right after I enter the phrase the program crashes on me.
Here is the program
#include <iostream>
#include <ctime>
#include "STACK.h"
using namespace std;
int main(void)
{
// Declare variables
time_t a;
STACK<char, 80> s;
STACK<char, 80> LR;
STACK<char, 80> RL;
char c;
char c1;
char c2;
// Displays the current time and date
time(&a);
cout << "Today is " << ctime(&a) << endl;
// Prompts the user to enter the string
cout << "Enter a phrase: ";
while(cin.get(c) && (c != '\n'))
{
if(isalpha(c))
{
c = toupper(c);
LR.PushStack(c);
s.PushStack(c);
}
}
// Copies s into RL in reverse order
while(!(s.EmptyStack() ) )
{
c = s.PopStack();
RL.PushStack(c);
}
// Checks for Palindrome
while(!(LR.EmptyStack() ) )
{
c1 = LR.PopStack();
c2 = RL.PopStack();
if( c1 != c2)
{
break;
}
}
// Displays the result
if(LR.EmptyStack() )
{
cout << "Palindrome";
}
else
{
cout << "Not a Palindrome";
}
return 0;
}
And here is the header (I am not allowed to change this)
#ifndef STACK_H
#define STACK_H
template <class T, int n>
class STACK
{ private: T a[n];
int counter;
public:
void MakeStack() { counter = 0; }
bool FullStack()
{ return (counter == n) ? true : false ; }
bool EmptyStack()
{ return (counter == 0) ? true : false ; }
void PushStack(T x)
{ a[counter] = x; counter++; }
T PopStack()
{ counter--; return a[counter]; }
};
#endif
You are not calling MakeStack, which will set STACK initial size (0).