oop in c++ (password generation) - c++

Object oriented programming in c++
I am learning oop in c++ and cannot use oop for this problem. oop might not be the best solution for this
but I want in it. This question might be simple but i could not solve this it shows
**error: cannot convert '<brace-enclosed initializer list>' to 'char' in assignment**
#include <iostream>
#include<ctype.h>
#include<time.h>
#include<stdlib.h>
#include<string>
#include<string.h>
#include<ctime>
using namespace std;
class passwordGenerate{
private:
char letters[56];
int length;
char password[100];
public:
passwordGenerate();
void setLength(int);
void setPassword(char p[]);
void displayPassword();
};
passwordGenerate::passwordGenerate(){
letters[56] = {'a','b','c','d','e',
'f','g','h','i','j',
'k','l','m','n','o',
'p','q','r','s','t',
'u','v','w','x','y','z',
'0','1','2','3','4','5','6','7','8','9',
'.','+','-','*','/',
'=','_',')','(','&',
'%','$','#','#','!',
'~',',','>','?','<'};
//it works when char letters[56] is given but does not work in this way.
}
void passwordGenerate::setLength(int l){
length = l;
}
void passwordGenerate::displayPassword(){
strcpy(password," ");
int random;
srand(time(0));
for(int x =0 ;x<length;x++){
random = rand()%55;
password[x] = letters[random];
}
for(int i=0;i<length;i++){
cout<<password[i];
}
}
int main()
{
passwordGenerate firstPassword;
int length;
cout<<"enter the length for password : ";
cin>>length;
firstPassword.setLength(length);
firstPassword.displayPassword();
return 0;
}

There is a fundamental difference between [] in those two
int x[5] = {1,2,3,4,5};
// ^----------------- size of the array
x[2] = 42;
//^--------------------- index of array element
So when you write
letters[56] = {'a',' .....
Then this is first accessing the array out of bounds (it has 56 elements and letters[56] is the 57-th). And you cannot assign {'a',... to a single char (type of elements).
To fix the problem I suggest you to work with std::string instead and use in-class initializer:
struct foo {
std::string letters{"abcdefghijklmnop...."};
};
Last but not least, I would suggest to name that member alphabet rather than letters, because it is not only letters.

Related

Discerning between struct indexing and size initialization

I'm trying to write a function that takes an array of structs and will sort the elements of the array alphabetically by accessing the first data member. I'm struggling to get the code to distinguish between when I'm referring to a data member versus initializing the size of an array. For example, the following code
void selectionSort(struct A[], int size)
{
int mindex;
for (int ct1 = 0; ct1 < size - 1; ct1++)
{
mindex = ct1;
for (int ct2 = ct1 + 1; ct2 < size; ct2++)
if (A[ct2].state < A[mindex].state)
mindex = ct2;
swap(A[mindex], A[ct1]);
}
}
complains that ct2 is not constant, when I'm clearly using it as an index. How would I get this to run correctly? That is, how can I get it to compare data members in their respective indices rather than think I'm initializing the size of a struct variable?
Edit The error message I am receiving is expression must have a constant value for the variable ct2.
I think you might have a problem with how you're creating your function. Usually, when you declare an array of structs it looks like this.
struct Student {
int uid;
string name;
};
Student studentArry[3];
You would use 'Student' or the name of your struct to initialize your array. For example, int arr[10] is an integer array of size 10 while Student arr[10] is a student array of size 10.
One other side note, if you're trying to create a function that is passed a struct you have to initialize the struct before you define the function. This code will work because the struct was declared before the function was.
#include <iostream>
using namespace std;
struct Student {
int uid;
string name;
};
void print(Student array[], int size){
for(int i = 0; i < size; i++){
cout << array[i].uid << endl;
cout <<array[i].name<< endl;
}
};
int main(){
Student StudentRecords[2] = {
{19, "John Smith"},
{21, "Jim Pop"}
};
print(StudentRecords, 2);
return 0;
}
The code below will not because the print function doesn't know what type student is.
#include <iostream>
using namespace std;
void print(Student array[], int size){
for(int i = 0; i < size; i++){
cout << array[i].uid << endl;
cout <<array[i].name<< endl;
}
};
int main(){
struct Student {
int uid;
string name;
};
Student StudentRecords[2] = {
{19, "John Smith"},
{21, "Jim Pop"}
};
print(StudentRecords, 2);
return 0;
}
So, all in all, I think you need to change how you're creating the parameter for the function and possible where you're declaring your struct.

Expected type got Element c++

Im trying to make a object / type that consists of an element of the periodic table. But when i try to use a vector of that object as a parameter, i get this error message expected a type, got ‘Element’
here is my code so far:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
Element(int AtomicNumm, string Symboll, string Namee, double Weightt,
int Neutronss, int Protonss, string ElectronConfigg) {
string Name = Namee;
int AtomicNum = AtomicNumm;
string Symbol = Symboll;
double Weight = Weightt;
int Neutrons = Neutronss;
int Protons = Protonss;
string ElectronConfig = ElectronConfigg;
}
string returnElement(vector<Element> vec, string input) { // error here
if (input.size() == 2) {
for (int i = 0; i < vec.length(); i++) {
}
}
return "";
}
int main(int argc, char*argv[]) {
vector<Element> PT;
string userinput (argv[1]);
return -1;
}
Also, im new to c++. If objects work completely differently here please let me know. (Coming from java)
That's because you haven't declared 'Element' in your program. Syntactically, it is close to definition of a constructor.
To make your program work, i guess you can do following modification to existing element:
class Element {
// your definition of element Here:
// also include default constructor without any implementation
Element() {}
};

Run-Time Check Failure #2 - Stack around the variable 'IDNumber' was corrupted

#include <iostream>
#include <string.h>
#include <time.h>
using namespace std;
struct MyID
{
char FirstName[10]; // array for lenight of the word.
char LastName[10]; // array for lenight of the word.
int IdNumber;
};
void InitializeArray(MyID IDNumber[], int Size);
//void SortTheArray(MyID IDNumber[], int Size);
int main(){
const int Size = 100;
MyID IDNumber[Size];
strcpy_s(IDNumber[Size].FirstName, "Aziz");
strcpy_s(IDNumber[Size].LastName, "LEGEND");
// I believe the error is around here.
InitializeArray(IDNumber, Size);
//SortTheArray(IDNumber, Size);
}
void InitializeArray(MyID IDNumber[], int Size){
//srand(time(0));
for (int i = 0; i < Size; i++){
//IDNumber[i].IdNumber = rand() %100 ;
cout<<IDNumber[i].FirstName<<endl;
IDNumber[i].LastName;
}
}
I have this problem, every time I want to test my function and struct, this error will prompt. Also, I want to see if my name will print correctly before continue to write rest program. The idea is I want to print same name every time without ask user to print name every time.
Also, I have upload the picture of result if you want to see it.
Because you are using arrays, you are experiencing buffer overrun error:
const int Size = 100;
MyID IDNumber[Size];
strcpy_s(IDNumber[Size].FirstName, "Aziz");
strcpy_s(IDNumber[Size].LastName, "LEGEND");
The expression IDNumber[Size] is equivalent to IDNumber[100].
In C++, array slot indices go from 0 to Size - 1. You are accessing one past the end of the array.
Edit 1: Initializing an array
Based on your comment, you can use a loop to initialize the slots in an array (vector):
struct Person
{
std::string first_name;
std::string last_name;
};
const unsigned int CAPACITY = 100;
int main()
{
std::vector<Person> database(CAPACITY);
Person p;
std::ostringstream name_stream;
for (unsigned int i = 0; i < CAPACITY; ++i)
{
name_stream << "Aziz" << i;
database[i].first_name = name_stream.str();
database[i].last_name = "LEGEND";
}
return 0;
}

Print struct inputs in alphabetic order C++

I want to print strings from a struct in alphabetic order, and I have got help from the thread How to alphabetically sort strings?, for the sorting. My problem is that when i run the compiler i get a sorted output but it includes a name from another struct. My code looks like this:
#include <iostream>
#include <set>
#include <algorithm>
#include <string>
using namespace std;
const int antalShops = 2;
const int antalWorkers = 5;
struct employ {
string workerName; int workerAge;
};
struct theMall{
string shopName; string shopType; int shopSize;
employ workerName; employ workerAge;
};
// Declaration of the structs
theMall Shops[antalShops] = {
{"GameStop","toy", 250,},
{"Frandsen", "cloth", 300,},
};
employ Workers[antalWorkers] = {
{"Andrea valente", 41},
{"Giovanni Pirolli", 25},
{"Marco Cipolli", 33},
{"Jensine Jensen", 19},
{"Andrea Jensen", 99},
};
// Functions for sorting and printing names
void print(const string& item) {
cout << item << endl;
}
void PrintWorkers(employ Workers[]) {
set<string> sortedWorkers;
for(int i = 0; i <= antalWorkers; ++i) {
sortedWorkers.insert(Workers[i].workerName);
}
for_each(sortedWorkers.begin(), sortedWorkers.end(), &print);
}
void PrintShops(theMall Shops[]) {
set<string> sortedShops;
for (int i = 0; i <= antalShops; ++i) {
sortedShops.insert(Shops[i].shopName);
}
for_each(sortedShops.begin(), sortedShops.end(), &print);
}
int main(int argc, const char * argv[])
{
PrintShops(Shops);
}
So I have the structs with workers and shops, but when I i try printing the shop names with the PrintShops(Shops) function i get the output:
Andrea Valente
Frandsen
GameStop
I have been looking through the code, but i can't find where the mistake is, anyone can see the error?
You go outside the bounds of the arrays in your loops
for (int i = 0; i <= antalShops; ++i) {
// Problem here ^^
The above loop will loop over indexes 0, 1 and 2, which is one to many for a two-entry array. This will lead to undefined behavior.
You have the same problem with the other sorting loop.

C++ code pass compling but return Segmentation fault

I have the following C++ code for practising sequence list and it passed the complier. However, when I try to run it, it returns Segmentation fault. Please help!! Thanks a lot.
main.cpp
#include <iostream>
#include <string>
#include "SeqList.h"
using namespace std;
int main() {
SeqList seq;
string vv[] = {"a", "b", "c", "d"};
for (int i = 0; i< 4; i++) {
seq.addElement(vv[i], i);
}
string* v = seq.getSeq();
for (int i=0; i<seq.getSeqSize(); i++) {
cout << v[i] <<endl;
}
return 0;
}
SeqList.h
#include<iostream>
#include<string>
using namespace std;
class SeqList {
private:
string seq[];
int size;
public:
void addElement(string, int);
void delElement(string, int);
string* getSeq();
int getSeqSize();
};
SeqList.cpp
#include <iostream>
#include <string>
#include "SeqList.h"
using namespace std;
string seq[100];
int size = 0;
string* SeqList::getSeq(){
return seq;
};
int SeqList::getSeqSize(){
return size;
};
void SeqList::addElement(string str, int pos) {
int i;
for (i = size; i > pos; i--) {
seq[i] = seq[i-1];
}
seq[i-1] = str;
size++;
};
Your segfault is happening because you're trying to access seq[i-1] in addElement when i = 0. This tries to access the memory outside of seq which causes a segfault. Try using seq[i] and seq[i+1] instead of seq[i-1] and seq[i], though you'll have to make sure you never call that code with more than 99 values or you'll run into a similar problem where the program tries to access memory past the end of seq.
Also, in SeqList.cpp
string seq[100];
int size = 0;
These lines are creating new variables, when it looks like you're trying to change the values you made in SeqList.h. To change those private values in your class you should either use a constructor or other function to initialize the values.