Pointer, Arrays, Structs, Getchar: C++ - c++

One of the functions of my program must be to add a structure element in an array with 1000 members, in my struct stay 'matrnr' as integer,'name' with pointer as char and 'abslv' as array with 30 elements,because I must write characterstring using char and the size of the signs has to be declared, and pointer too,because the sum of all char-strings have to be smaller or equal to 30.
I am not allowed to use any library functions,only printf,getchar,scanf,cin and cout from iostream and stdio.h
My Questions about the struct:The name must also be implement with char,do I have to write array?
const int maxstudenten = 1000;
const int MAX = 30;
struct student_t {
int matrnr;
char* name[MAX];
char** abslv[MAX];
};
I have also problems in the following spaces in this function (In the comments):
int land (student_t *feld[maxstudenten], int i) { //I is my counter for
//the current size
student_t *pstudentanlegen= new student_t; //Write a new student
printf("Matrikelnummer:...."); //Enrolment number
std::cin>>pstudentanlegen->matrnr; //Stack->enrolment number
if (pstudentanlegen->matrnr>1 && pstudentanlegen->matrnr<999999) {
//the enrolment number must be >1 and <999999
if (binaeresuche(&feld[maxstudenten],i,(pstudentanlegen->matrnr))!=0) { //It examins if a student with this name already exists
std::cout<<"Student mit diesem Matrikelnummer ist schon vorhanden"<<std::endl; //Student with this enr.nr exists
return i;
}else {
printf("\nName:.....");
pstudentanlegen->name=getchar(); //Pointer->name
//Here I cant write anything although I have written getchar
std::cout<<std::endl;
int zaehler=0;
std::cout<<"Möchten Sie Lehrveranstantungen hinfügen? j=ja,n=nein"<<std::endl;
//Do you want to add lectures?
char a;
std::cin>>a;
if(a=='j' && zaehler<MAX) { //zaehler=my second counter
//for the lectures
std::cout<<"Lehrveranstaltung:"; //Lecture:
pstudentanlegen->abslv[MAX]=getchar();
//insupportable types of allocation of int to char* [30]
zaehler++;
}
i++;
} //Anhängen (sortiert nach Matrikelnummer)
//add(sorted towards number)
int position=0;
while(position<maxstudenten && pstudentanlegen->matrnr>feld[position]->matrnr) { //Invalid conversion of int in char**
position++;
}
}return i;
}

Related

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;
}

How to search array of structs for a string(name) and return info for that string(name)?

With this program, when i type in a name nothing is returned.
How would I fix this?
There are 1000 lines of info that looks like this:
114680858 19670607 Matilda Vincent MI
114930037 19471024 Desdemona Hanover ID
115550206 19790110 Xanadu Perlman ND
116520629 19630921 Alexander Hall SD
117050976 19301016 David Lamprey GA
119610646 19650202 Thomas Porlock IL
120330928 19621126 Cary Cartman NC
etc......
Code:
struct employees
{
int ss_number;//social security
int dob;//date of birth YYYY/MM/DD Ex.) 19870314=1987/03/14
string f_name;
string l_name;
string state; //state of residence
};
void read_file()//read file into array of 1000 structs
{
ifstream data("/home/www/class/een118/labs/database1.txt");
employees array[1000]
if(!data.fail())
{
int i;
for(int i=0;i<1000;i++)
{
data>>array[i].ss_number
>>array[i].dob
>>array[i].f_name
>>array[i].l_name
>>array[i].state;
}
for(int i=0;i<1000;i++)
{
cout<<array[i].ss_number>>" "<<array[i].dob>>" "<<array[i].f_name>>" "<<
array[i].l_name>>" "<<array[i].state;
}
}
}
void print_person(employees e)
{
cout<<e.ss_number>>" "<<e.dob>>" "<<e.f_name>>" "<<e.l_name>>" "<<e.state;
}
void search(employees array[])//type in name and get that persons ss_number,dob etc...
{
string first;
string last;
cout<<"Enter name";
cin>>first>>last;
for(int i=0;i<1000;i++)
{
if(array[i].f_name==first && array[i].l_name==last)
{
print_person(array[i]);
}
}
}
void main()
{
employees array[10];
read_file();
search(array);
}
// ...
There are two arrays. One is in main, the other is in read_file. They have the same name but are different sizes.
The array in read_file has no relationship to the array in main. You passed the array to search but not to read_file. I suggest you pass the array to read_file by reference and remove the array declaration in read_file.
Better yet, eliminate the array and use std::vector. It would be std::vector<employees>.
Edit 1: Searching the array
In your search function you will need to pass two additional parameters: array capacity and the number of records in the array. If you used std::vector<employees>, you could get the number of employees in the array by:
number_of_employees = array.size();
The for loop would use iterators:
std::vector<employees>::const_iterator iter;
for (iter = array.begin(); iter != array.end(); ++iter)
{
// process array slot by dereferencing it:
employee e = *iter;
cout << e << "\n"; // This could happen if you overloaded operator <<
}
Otherwise, with an array, your loop would look like:
void search(employees array[], unsigned int capacity, unsigned int employees_in_array)
{
for (unsigned int i = 0; i < employees_in_array; ++i)
{
cout << array[i];
}
}
A nice improvement is that this search function doesn't hardcode the size. So you can change the size from 10 (in main) to 1000 without modifying the search function.
If you sort your container, you can use a binary search.
See: std::binary_search, std::find, std::lower_bound, std::upper_bound

Sending an array between two functions C++

I am trying to send a array of 15 integers between two functions in C++. The first enables the user to enter taxi IDs and the second functions allows the user to delete taxi IDs from the array. However I am having an issue sending the array between the functions.
void startShift ()
{
int array [15]; //array of 15 declared
for (int i = 0; i < 15; i++)
{
cout << "Please enter the taxis ID: ";
cin >> array[i]; //user enters taxi IDs
if (array[i] == 0)
break;
}
cout << "Enter 0 to return to main menu: ";
cin >> goBack;
cout << "\n";
if (goBack == 0)
update();
}
void endShift ()
{
//need the array to be sent to here
cout << "Enter 0 to return to main menu: ";
cin >> goBack;
cout << "\n";
if (goBack == 0)
update();
}
Any help is great valued. Many thanks.
Since the array has been created on the stack, you would just need to pass the pointer to the first element, as an int*
void endshift(int* arr)
{
int val = arr[1];
printf("val is %d", val);
}
int main(void)
{
int array[15];
array[1] = 5;
endshift(array);
}
Since the array is created on the stack, it will no longer exist once the routine in which it was created has exited.
Declare the array outside of those functions and pass it to them by reference.
void startShift(int (&shifts)[15]) {
// ...
}
void endShift(int (&shifts)[15]) {
// ...
}
int main() {
int array[15];
startShift(array);
endShift(array);
}
This isn't exactly pretty syntax or all that common. A much more likely way to write this is to pass a pointer to the array and its length.
void startShift(int* shifts, size_t len) {
// work with the pointer
}
int main() {
int array[15];
startShift(array, 15);
}
Idiomatic C++ would be different altogether and use iterators to abstract away from the container, but I suppose that is out of scope here. The example anyway:
template<typename Iterator>
void startShift(Iterator begin, Iterator end) {
// work with the iterators
}
int main() {
int array[15];
startShift(array, array + 15);
}
You also wouldn't use a raw array, but std::array.
It won't work to use a local array in the startShift() function. You are best off to do one or more of the following:
Use an array in the function calling startShift() and endShift() and pass the array to these functions, e.g.:
void startShift(int* array) { ... }
void endShift(int* array) { ... }
int main() {
int arrray[15];
// ...
startShift(array);
// ...
endShift(array);
// ...
}
Don't use built-in arrays in the first place: use std::vector<int> instead: that class automatically maintains the current size of the array. You can also return it from a function altough you are probably still best off to pass the objects to the function.
void endShift (int* arr)
{
arr[0] = 5;
}

Hash table(linear probing)

I am making a hash table using linear probing and i have to resize the array when ever the load factor i.e (no. of elements entered in hashtable)/(size of hashtable), becomes greater than 0.5, i have to resize the array.I am doing the resizing by initializing a pointer in a class which contains functions related to hashtable.I am putting the pointer equal to an array of a struct (struct only contains a string) of size 100.every time load factor becomes greater than 0.5, i resize the array by making a new array of double the previous size and point the pointer to the new array.I also have an int which stores current size of array and which is updated with every instance in which resize function is used.The number of elements inserted are incremented with every call to insert function.Am I doing this correctly?Below is my code
#include <cstring>
#include <vector>
#include <math.h>
#include <iomanip>
using namespace std;
int power(int a,int b)
{
for (int i=0;i<b;i++)
{
a*=a;
}
return a;
};
struct Bucket
{
string word;
};
const int size=100;
class LProbing
{
private:
int a; //a constant which is used in hashing
int cursize; //current size of hash table
Bucket *Table; //pointer to array of struct
int loadfactor; //ratio of number of elements entered over size of hashtable
int n; //number of elements entered
Bucket table[size]; //array of structs
public:
LProbing(int A); //constant is decided by user
void resize();
void insert(string word);
void Lookup(string word);
};
LProbing::LProbing(int A)
{
cursize=size;
a=A;
Table=table;
loadfactor=0; //initially loadfactor is 0 as number of elements entered are 0
n=0;
}
void LProbing::resize()
{
cout<<"resize"<<endl;
loadfactor=n/cursize; //ensuring if resize needs to be done
if (loadfactor<=0.5)
{
return;
}
const int s=2*cursize;
Bucket PTable[s];
for (int i=0;i<cursize;i++)
{
if (Table[i].word.empty())
continue;
//rehashing the word onto the new array
string w=Table[i].word;
int key=0;
for (int j=0;j<w.size();j++)
{
unsigned char b=(unsigned char)w[j];
key+=(int)power(a,i)*b;
}
key=key%(2*cursize);
PTable[key].word=w; //entering the word in the new array
}
Table=PTable; //putting pointer equal to new array
cursize=2*cursize; //doubling the current size of array
}
void LProbing::insert(string word)
{
cout<<"1"<<endl;
n++; //incrementing the number of elements entered with every call to insert
//if loadfactor is greater than 0.5, resize array
loadfactor=n/cursize;
if (loadfactor>0.5)
{
resize();
}
//hashing the word
int k=0;
for (int i=0;i<word.size();i++)
{
unsigned char b=(unsigned char)word[i];
int c=(int)((power(a,i))*b);
k+=c;
cout<<c<<endl;
}
int key=0;
key=k%cursize;
cout<<key<<endl;
//if the respective key index is empty enter the word in that slot
if (Table[key].word.empty()==1)
{
cout<<"initial empty slot"<<endl;
Table[key].word=word;
}
else //otherwise enter in the next slot
{
//searching array for empty slot
while (Table[key].word.empty()==0)
{
k++;
key=k%cursize;
}
//when empty slot found,entering the word in that bucket
Table[key].word=word;
cout<<"word entered"<<endl;
}
}
#include "Linear Probing.cpp"
#include <fstream>
using namespace std;
int main()
{
LProbing H(35);
ifstream fin;
fin.open("dict.txt");
vector<string> D;
string d;
while (getline(fin,d))
{
if (!d.empty())
{
D.push_back(d);
}
}
fin.close();
for (int i=0;i<D.size();i++)
{
H.insert(D[i]);
}
system("PAUSE");
return 0;
}
You may find it helpful somewhere:
http://www.cs.rmit.edu.au/online/blackboard/chapter/05/documents/contribute/chapter/05/linear-probing.html
You are dealing with big numbers and variable "key" is overflowing in:
key += (int)power(a,i)*b
It looks like loadfactor is calculated as int/int so it will stay 0 until it reaches 1. Try casting the inputs to the division into floats.

Constructors and array of object in C++

I'm trying to create an application in C++. In the application I have the default constructor and another constructor with 3 arguments.
The user is providing from the keyboard an integer that it will be used to create an array of objects using the non default constructor.
Unfortunately I haven't been able to finish it till now, since I'm having issues with the creation of the array of objects that they will use the non default constructor.
Any suggestions or help?
#include<iostream>
#include<cstring>
#include<cstdlib>
#include <sstream>
using namespace std;
class Station{
public:
Station();
Station(int c, char *ad, float a[]);
~Station();
void setAddress(char * addr){
char* a;
a = (char *)(malloc(sizeof(addr+1)));
strcpy(a,addr);
this->address = a;
}
void setCode(int c){
code=c;
}
char getAddress(){
return *address;
}
int getCode(){
return code;
}
float getTotalAmount(){
float totalAmount=0;
for(int i=0;i<4;i++){
totalAmount+=amount[i];
}
return totalAmount;
}
void print(){
cout<<"Code:"<<code<<endl;
cout<<"Address:"<<address<<endl;
cout<<"Total Amount:"<<getTotalAmount()<<endl;
cout<<endl;
}
private:
int code;
char *address;
float amount[4];
};
Station::Station(){
code= 1;
setAddress("NO ADDRESS GIVEN");
amount[0]= 0.0;
amount[1]= 0.0;
amount[2]= 0.0;
amount[3]= 0.0;
}
Station::Station(int c, char *ad, float a[]){
if( (c>=1&& c<=10 ) ){
code=c;
address=ad;
for(int i=0;i<4;i++){
amount[i]=a[i];
}
}else{
code= 1;
setAddress("NO ADDRESS GIVEN");
amount[0]= 0.0;
amount[1]= 0.0;
amount[2]= 0.0;
amount[3]= 0.0;
}
}
Station::~Station(){
}
int main(){
int size,code;
char *addrr;
addrr = (char *)(malloc(sizeof(addrr+1)));
float mes[4];
do{
cout<<"size of array:";
cin>>size;
}while(size<=0 || size>=11);
// Station *stations= new Station[size];
// Station** stations = new Station*[size];
Station stations[size];
for(int i=0;i<size;i++){
cout<<"code:";
cin>>code;
cout<<"address:";
cin>>addrr;
double amo=0;
for(int k=0;k<4;k++){
cout<<"values"<<k+1<<":";
cin>>mes[k];
}
}
/*
for(int q=0;q<size;q++){
stations[q].print();
}
*/
return 0;
}
the values that I'll take from cin I want to assign them to the objects of the array!
You can either create the array default-initialized and then fill the array with the wanted object:
foo arr[10];
std::fill(arr, arr+10, foo(some, params));
Alternatively you could use std::vector and do just:
std::vector<foo> arr(10, foo(some, params));
In C++0x, you can use braced-init-list in new expression, which means you can do this:
#include <iostream>
class A
{
public:
A(int i, int j){std::cout<<i<<" "<<j<<'\n';}
};
int main(int argc, char ** argv)
{
int *n = new int[3]{1,2,3};
A *a = new A[3]{{1,2},{3,4},{5,6}};
delete[] a;
delete[] n;
return 0;
}
Compiled under g++ 4.5.2, using g++ -Wall -std=c++0x -pedantic
Since you say you can't use std::string, this is going to be much more difficult. The line addrr = (char *)(malloc(sizeof(addrr+1))); is not doing what you think it is. Instead of using malloc to allocate on the heap and since there is no free (which will lead to a memory leak), it will be much easier if we allocate on the stack with a predetermined buffer size: char addrr[BUFFER_LENGTH]. With BUFFER_LENGTH defined before Station's declaration as const int BUFFER_LENGTH = 20; or some other appropriate length.
To use the non-default constructor, adding stations[i] = Station(c, addrr, mes); at the end of the for loop will do the trick.
for(int i=0;i<size;i++){
cout<<"code:";
cin>>code;
cout<<"address:";
cin>>addrr; // do not read in strings longer than 20 characters or increase BUFFER_LENGTH’s size
double amo=0;
for(int k=0;k<4;k++){
cout<<"values"<<k+1<<":";
cin>>mes[k];
}
stations[i] = Station(c, addrr, mes);
}
But, this is not going to work properly since the constructor is copying the addrr pointer, not the data. I would recommend also changing the data member char *address to char address[BUFFER_LENGTH]. Then, in the constructor you can replace the line address=ad; with strcpy(address, ad);.
Note: setAddress and getAddress will now need to be updated.
Another line that is troubling is Station stations[size];. This is non-standard since size is not a known at compile time. Either use Station *stations= new Station[size]; and remember to delete or if you can use a std::vector, use std::vector<Station> stations(size);
If you do go the std::vector route, using push_back will work nicely:
std::vector<Station> stations;
for(int i=0;i<size;i++){
cout<<"code:";
cin>>code;
cout<<"address:";
cin>>addrr;
double amo=0;
for(int k=0;k<4;k++){
cout<<"values"<<k+1<<":";
cin>>mes[k];
}
stations.push_back( Station(c, addrr, mes) );
}