Check if a string is a base 16 number - c++

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

Related

Struct doesn't print with cout

I'm trying to print the structure in an array whose int prejetih member is highest.
#include <iostream>
using namespace std;
struct Tekma {
int prejetih;
};
Tekma najvec_kosev(Tekma tekme[]) {
int maksi = 0, index = 0;
for (int i = 0;i < 2;i++) {
if (maksi < tekme[i].prejetih) {
index = i;
maksi = tekme[i].prejetih;
}
}
return tekme[index];
}
void vpis(Tekma tekme[]) {
for (int i = 0;i < 2;i++)
cin >> tekme[i].prejetih;
}
int main() {
Tekma tekme[2];
vpis(tekme);
cout << najvec_kosev(tekme);
}
The compiler reports
C++ no operator matches these operands
operand types are: std::ostream << Tekma
over cout << najvec_kosev(tekme);
Here using a solution with std::vector and fixing your cout problem:
#include <iostream>
#include <vector>
using namespace std;
struct Tekma {
int prejetih;
};
Tekma najvec_kosev(vector<Tekma>& tekme) {
Tekma lowest = tekme[0]
for(auto& t : tekme) {
if(lowest.prejetih < t.prejetih) {
lowest = t;
}
}
return lowest ;
}
void vpis(vector<Tekma>& tekme) {
int input;
while(true) {
cin >> input;
// Check if the input is valid else quit the loop.
if(input == valid) {
Tekma newStruct = {input};
tekme.push(newStruct);
}
else {
// Stop the loop
break;
}
}
}
int main() {
vector<Tekma> tekme;
vpis(tekme);
cout << najvec_kosev(tekme).prejetih; // This fixes your error.
}

Unknown Type Name when using threads

I am trying to find the minimum vertex cover by giving the vertex and edge input in specific format from the user using threads. Here is my code:
#include <iostream>
#include <string>
#include <sstream>
#include <fstream>
#include <cctype>
#include <list>
#include <set>
#include <vector>
#include <climits>
#include <memory>
#include <algorithm>
#include <pthread.h>
#include <unistd.h>
#include "minisat/core/Solver.h"
using namespace std;
static void *AVC2_Vertex_Cover(void *);
void min_vertex_cover_algorithm(Graph &graph_builder){
int ret;
pthread_t AVC2_thread;
ret = pthread_create(&AVC2_thread, NULL, AVC2_Vertex_Cover, &graph_builder);
if(ret)
exit(1);
pthread_join(AVC2_thread, NULL);
pthread_exit(NULL);
}
struct Edge{
unsigned v1,v2;
};
typedef std::vector<unsigned> Vertex_vector;
typedef std::list<unsigned > Vertex_Adjacency_list;
typedef std::vector<Vertex_Adjacency_list> Adjacency_Traversal_list;
struct Graph{
std::size_t no_of_edges;
Adjacency_Traversal_list adjacency_list;
void initialize_graph(unsigned vertices_number);
void construct_edge(Edge edge);
void clear(unsigned vertex);
};
void Graph::initialize_graph(unsigned num){
adjacency_list.clear();
no_of_edges = 0;
adjacency_list.resize(num,{});
}
void Graph::construct_edge(Edge edge) {
auto &literal_1 = adjacency_list[edge.v1];
auto &literal_2 = adjacency_list[edge.v2];
literal_1.push_back(edge.v2);
literal_2.push_back(edge.v1);
no_of_edges ++;
}
void *AVC2_Vertex_Cover(void *input)
{
Graph g = *(const Graph *)input;
unsigned int V = g.adjacency_list.size();
bool visited[V];
for (int i=0; i<V; i++)
visited[i] = false;
for (int u=0; u<V; u++)
{
if (visited[u] == false)
{
for(int x : g.adjacency_list[u])
{
int v = x;
if (visited[v] == false)
{
visited[v] = true;
visited[u] = true;
break;
}
}
}
}
// Print the vertex cover
std::cout << "APPROX-VC-2: ";
for (int i=0; i<V; i++){
if (visited[i])
if(i == V-1)
cout << i << std::endl;
else
cout << i << ",";
}
}
void *IO_thread(void *)
{
Graph &graph_builder = *new Graph();
char character_input;
string my_input;
unsigned int no_of_vertices = 0;
string edge_stream;
char prev_choice = ' ';
while (getline(cin, my_input))
{
istringstream stream_string(my_input);
while (stream_string >> character_input)
{
character_input=(toupper(character_input));
try
{
switch (character_input)
{
case 'V' :
if (prev_choice == 'V')
{
cerr << "Error: V must be followed by E only.\n";
break;
}
else
{
stream_string >> no_of_vertices;
if(no_of_vertices <= 0)
{
throw "Invalid number of vertices";
}
graph_builder.initialize_graph(no_of_vertices);
prev_choice = 'V';
break;
}
case 'E' :
{
unsigned int flag_Entry = 0;
if ( prev_choice == 'E')
{
cerr << "Error: V and E always occur together.\n ";
break;
}
else
{
stream_string >> edge_stream;
istringstream edge_stream_character(edge_stream);
char edg_char;
unsigned int temp = 0;
unsigned int v1;
unsigned int v2;
edge_stream_character >> edg_char;
while (edg_char != '}')
{
edge_stream_character >> edg_char;
if (edg_char == '}')
{
flag_Entry = 1;
break;
}
else
{
edge_stream_character >> temp;
v1 = temp;
edge_stream_character >> edg_char;
edge_stream_character >> temp;
v2 = temp;
edge_stream_character >> edg_char;
edge_stream_character >> edg_char;
if (v1 >= no_of_vertices || v2 >= no_of_vertices)
{
cerr << "Error: Vertex out of range.\n";
graph_builder.adjacency_list.clear();
break;
}
graph_builder.construct_edge({v1,v2});
}
}
if(flag_Entry == 1)
{
prev_choice = 'E';
break;
}
min_vertex_cover_algorithm(graph_builder);
prev_choice = 'E';
break;
}
}
}
}
catch (const char* err)
{
cerr << "Error:" << err << endl;
}
}
}
return 0;
}
int main(int argc, char **argv){
int ret;
pthread_t IO_thread;
ret = pthread_create(&IO_thread, NULL, IO_thread,NULL);
if(ret)
return 1;
pthread_join(IO_thread,NULL);
pthread_exit(NULL);
}
I am getting an error:
unknown type name 'Graph'
void min_vertex_cover_algorithm(Graph &graph_builder){
I am not able to find why this error is occuring. It will be very helpful if I get some solutions.
Just like you, the compiler will read from top to bottom. When it reaches the line:
void min_vertex_cover_algorithm(Graph &graph_builder){
It has to go, ok, lets use a Graph reference. It will look for the declaration of a Graph, which it cannot find, because you have declared (and defined) it below. To solve this, give the compiler a hint. Declare the Graph above the function with:
struct Graph;
void min_vertex_cover_algorithm(Graph &graph_builder){
Or simply move the whole struct definition above the function.

How can i iterator through all possible nodes and determine if it is Eulerian Circuit?

I can't seem to iterate through all the nodes. It goes through only 1 or two nodes and fails to return true for any case. I want the program to iterator through the node multiple times to get all possible outcome, but still be Eulerian circuit. This is just a small example. To determine if it is Eulerian Circuit, it must pass through the edge only once. Whenever i tried the recursive function DFSUtil, it will stop at the first node or the 2nd node.
Example:
start = A
End = C
A connect to B
A connect to C
B connect to A
B connect to C
C connect to B
Result: 2 path
A -> B -> C -> B -> A -> C
A -> B -> A -> C -> B -> C
#include <iostream>
#include <string>
#include <string.h>
#include <sstream>
#include <stdio.h>
#include <stack>
#include <vector>
using namespace std;
unsigned int V;
class node
{
public:
string Enzyme;
vector<node> connection;
node(string Enzyme)
{
this->Enzyme = Enzyme;
}
bool isEulerCircuit();
bool isConnected();
string DFSUtil(unsigned int v,bool visited[]);
void add_edge(node &n)
{
connection.push_back(n);
cout << Enzyme << " connected to " << n.Enzyme << endl;
}
};
string node::DFSUtil(unsigned int v,bool visited[])
{
visited[v] = true;
vector<node>::iterator it;
string res;
for(it = connection.begin(); it != connection.end(); it++)
{
cout << (*it).Enzyme << endl;
if(!visited[v])
{
res+= (*it).Enzyme;
DFSUtil(v,visited);
}
}
return res;
}
bool node::isEulerCircuit()
{
if (isConnected() == false)
{
return false;
}
return true;
}
bool node::isConnected()
{
bool visited[V];
for(int i = 0; i < V; i++)
{
visited[i] = false;
}
int n=3;
DFSUtil(n,visited);
for (int i = 0; i < V; i++)
{
if (visited[i] == false)
{
return false;
}
}
return true;
}
int main()
{
vector<node> nod;
string A = "A";
string B = "B";
string C = "C";
nod.push_back(A);
nod.push_back(B);
nod.push_back(C);
for(int i = 0; i < nod.size(); i++)
{
V = i;
}
cout << endl;
nod[0].add_edge(nod[1]);
nod[0].add_edge(nod[2]);
nod[1].add_edge(nod[0]);
nod[1].add_edge(nod[2]);
nod[2].add_edge(nod[1]);
if(nod[0].isEulerCircuit())
{
cout << "HI" << endl;
}
else
{
cout << "BYE" << endl;
}
return 0;
}

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.

C++ Palindrome program

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