C++ Palindrome program - c++

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).

Related

How to make sure that two strings only have certain alphabets in c++

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.

Error Mulitple Definition of [closed]

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

Check if a string is a base 16 number

I've been trying to solve this task, but I had no positive results.
So, my task is to check if a string is a base 16 number.
example : s="1AB", it will show YES 427
Here is my code.
#include <iostream>
#include <string.h>
using namespace std;
int power (int a, int b)
{
if(b==1) return a;
else return a*power(a,b-1);
}
void conv(char s[],int &n)
{
int S=0,i,p=0;
for(i=n-1;i>=0;i--)
{
if(s[i]>='0' && s[i]<='9')
S+=(s[i]-48) * power(16,p); //ex:s[i]='1' ==> S+=(49-49)*...
else S+=(s[i]-55) * power(16,p); //s[i]='A' ==> S+=(65-55) *...
p++;
}
}
int main()
{
int n,i,k=0;
char s[255];
cin.get(s,255);
cin.get();
n=strlen(s);
for(i=0;i<n;i++)
{
if(strchr("0123456789ABCDEF",s[i])) k++;
}
if(k==0) cout<<"not in base 16";
else{
conv(s,n); cout<<s;}
return 0;
}
If you want almost clean solution, you can check mine:
#include <iostream>
using namespace std;
bool IsHex(string& in) {
for (char d : in) {
if (!isxdigit(d)) return false;
}
return true;
}
int Convert(string& in) {
int val = 0;
for (char d : in) {
val = val * 16 + (isdigit(d)? d - '0' : 10 + (isupper(d)? d - 'A' : d - 'a'));
}
return val;
}
int main() {
string in;
cin >> in;
if (!IsHex(in)) cout << "Not a correct hex number" << endl;
else cout << "YES " << Convert(in) << endl;
return 0;
}
And I have made some changes in your code to make it work. You can easily find out changes.
#include <iostream>
#include <string.h>
using namespace std;
int power (int a, int b)
{
if (b == 0) return 1;
if(b==1) return a;
else return a*power(a,b-1);
}
int conv(char s[],int &n)
{
int S=0,i,p=0;
for(i=n-1;i>=0;i--)
{
if(s[i]>='0' && s[i]<='9')
S+=(s[i]-48) * power(16,p); //ex:s[i]='1' ==> S+=(49-49)*...
else S+=(s[i]-55) * power(16,p); //s[i]='A' ==> S+=(65-55) *...
p++;
}
return S;
}
int main()
{
int n,i,k=0;
char s[255];
cin.get(s,255);
cin.get();
n=strlen(s);
for(i=0;i<n;i++)
{
if(!strchr("0123456789ABCDEF",s[i])) break;
}
if(i < n) cout<<"not in base 16";
else{
cout << conv(s,n) << endl;}
return 0;
}
You can just use std::isxdigit, for example:
#include <cctype>
#include <string>
#include <iostream>
bool IsThisStringAHexNumber(std::string const &str)
{
for (size_t i = 0, n = str.length(); i < n; ++i)
if (!std::isxdigit(str[i]))
return false;
return true;
}
int main()
{
std::cout << std::boolalpha << IsThisStringAHexNumber("298722h2jjh") << std::endl;
std::cout << std::boolalpha << IsThisStringAHexNumber("2abc66f") << std::endl;
return 0;
}
Prints:
false
true

C++: How to check whether same number of letters 'a' and 'b' are present in a string using a stack

I need to check if number of letters "a" is equal to number of letters "b" using stack.
So i understand logic of this task, but my code doesn't work.
Logic:
If current letter == to letter in stack (s.pop()) or stack is empty then push into stack
else pop from stack
after end of cycle check size of stack. If it is empty so number of letters is equl, else not
I already have class stack
#include <string>
#include <iostream>
#include <cstdlib> // для system
using namespace std;
class stack {
public:
stack() {
ptr = 0;
}
~stack() {}
bool push(int val) {
if (ptr >= MAXSIZE) return false;
body[ptr++] = val; return true;
}
bool pop(int *val) {
if (ptr == 0) return false;
*val = body[--ptr]; return true;
}
bool empty() {
return ptr == 0;
}
private:
enum { MAXSIZE = 100 };
int body[MAXSIZE];
int ptr; // указатель на последний элемент
};
int main()
{
stack s;
std::string str;
std::cout << "Enter your ab string ";
getline(std::cin, str);
for (int c : str) {
if (c == s.pop(&c) || s.empty()) {
s.push(c);
}
else {
s.pop(&c);
}
}
if (s.empty()) {
cout << "YES\n";
system("pause");
return 0;
}
else {
cout << "NO\n";
system("pause");
}
}
result for abab, aabb, ab 'YES'
for aaabb, aba 'NO'
You need a method to look at current value on top of stack without popping it:
class stack {
...
int top() { // never use on an empty stack
return body[ptr-1];
}
...
};
That way you can write:
for (int c : str) {
// short circuit evaluation ensures that top is never called on an empty stack
if (s.empty() || (c == s.top()) {
s.push(c);
}
else {
s.pop(&c);
}
If you cannot, you must push back the popped value if it should not have been popped:
for (int c : str) {
int d;
if (! s.pop(&d)) { // s was empty
s.push(c);
}
else if (c == d) {
s.push(d); // should not have been popped
s.push(c);
}
}
You can push everytime you see a.
for (int c = 0; c < str.size() ; ++c) {
if (str[c] == 'a') s.push('a');
}
if ((s.size() * 2) == str.size()) cout << "YES\n"; else cout << "NO\n";
stack::size can be implemented this way:
int stack::size() {
return ptr;
}

Palindrome class help in C++ [closed]

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 6 years ago.
Improve this question
Hi i am trying to write a palindrome class but am getting the wrong results.
I need to create a Palindrome class and return whether the phrase is a Palindrome.
Here is my code.
Palindrome.h:
#ifndef PALINDROME_H
#define PALINDROME_H
#include <iostream>
#include<cstring>
using namespace std;
class Palindrome{
private:
char str[1024];
char s1[1024];
char s2[1024];
int a;
int b;
public:
Palindrome(char s2[1024], int a, int b)
{
s2[1024] = { 0 };
a = 0;
b = 0;
}
void removeNonLetters(char str[]);
void lowerCase(char s1[]);
bool isPalindrome(char s2[], int a, int b);
}; // End of class definition
#endif
Palindrome.cpp:
#include "Palindrome.h"
void Palindrome::removeNonLetters(char str[])
{
char s1[1024] = { 0 };
int j = 0;
int l1 = strlen(str);
for (int i = 0; i < l1; i++)
{
if (str[i] <= '9' && str[i] >= '0')
{
s1[j++] = str[i];
}
else if ((str[i] >= 'A' && str[i] <= 'Z')
|| (str[i]) >= 'a' && str[i] <= 'z')
{
s1[j++] = str[i];
}
}
cout << s1 << endl;
}
void Palindrome::lowerCase(char s1[])
{
char s2[1024] = { 0 };
int l2 = strlen(s1);
int g = 0;
for (int i = 0; i < l2; i++)
{
if (s1[i] >= 'a' && s1[i] <= 'z')
{
s2[g++] = s1[i];
}
else if (s1[i] >= 'A' && s1[i] <= 'Z')
{
s2[g++] = s1[i] + 32;
}
}
cout << s2 << endl;
}
bool Palindrome::isPalindrome(char s2[], int a, int b)
{
if (a >= b)
return true;
cout << "Yes" << endl;
if (s2[a] != s2[b])
return false;
else
return isPalindrome(s2, a + 1, b - 1);
cout << "No" << endl;
}
Main.cpp:
#include "Palindrome.h"
int main()
{
char str[1024] = { 0 };
char s1[1024] = { 0 };
char s2[1024] = { 0 };
cout << "input a string:" << endl;
cin.getline(str, sizeof(str));
Palindrome removeNonLetters(char str[]);
Palindrome lowerCase(char s1[]);
int length = strlen(s2);
Palindrome isPalindrome(s2, 0, length - 1);
return 0;
}
You teacher may not like this, but this is how we do it in the real world.
First things first, reach for the standard library:
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
A function to strip non-alpha characters from a string:
std::string strip(std::string s)
{
s.erase(std::remove_if(std::begin(s),
std::end(s),
[](auto c) { return !std::isalpha(c); }),
std::end(s));
return s;
}
A function to transform a string to lower case:
std::string to_lower(std::string s)
{
std::transform(std::begin(s),
std::end(s),
std::begin(s),
[](auto c) { return std::tolower(c); });
return s;
}
A function to check that a string is the same in reverse as it is forwards:
bool is_palindrome(const std::string& s)
{
return std::equal(std::begin(s), std::end(s),
std::rbegin(s), std::rend(s));
}
Putting it all together in a test:
int main()
{
auto word = std::string("a!b B <>A");
if (is_palindrome(to_lower(strip(word)))) {
std::cout << "palindrome" << std::endl;
}
else {
std::cout << "not palindrome" << std::endl;
}
return 0;
}
Complete listing:
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
std::string strip(std::string s)
{
s.erase(std::remove_if(std::begin(s),
std::end(s),
[](auto c) { return !std::isalpha(c); }),
std::end(s));
return s;
}
std::string to_lower(std::string s)
{
std::transform(std::begin(s),
std::end(s),
std::begin(s),
[](auto c) { return std::tolower(c); });
return s;
}
bool is_palindrome(const std::string& s)
{
return std::equal(std::begin(s), std::end(s),
std::rbegin(s), std::rend(s));
}
int main()
{
auto word = std::string("a!b B <>A");
if (is_palindrome(to_lower(strip(word)))) {
std::cout << "palindrome" << std::endl;
}
else {
std::cout << "not palindrome" << std::endl;
}
return 0;
}
There are many things wrong with your code. I hope these pointers help:
You should be using std library.
Why does the constructor for the class take any parameters? Nothign uses them
Why are there any member variables? Nothing uses them.
Why are the functions in a class at all? They're just functions - they should be in a functions library or similar.
The functions just write to cout so are useless.
Your main function doesn't even seem to call the functions correctly.
I tried this:
char str[1024] = { 0 };
cout << "input a string:" << endl;
cin.getline(str, sizeof(str));
int length = strlen(str);
Palindrome a(str,0, length);
a.removeNonLetters(str);
a.lowerCase(str);
a.isPalindrome(str, 0, length - 1);
cin.getline(str, sizeof(str));
return 0;
I don't get the exception but get the following output:
input a string:
EVIL rats on no star **** live
EVILratsonnostarlive
evilratsonnostarlive
Yes
However this works too:
input a string
hello
hello
hello
Yes
So the first two functions seem to work (if removing spaces was also intentional) but the third does not.