Error handling failure - visual-c++

I'm new and a novice programmer and trying to learn.. I've been trying to do a library program using structures, with the following functions I've created. add a new customer, find number of customers, print details of a customer,borrow book,reserve book, return book
what I failed is that ; when I add a new customer my program asks for name, address and Id, and, and I want my program to give an error message when I try to register a new customer with an already existing id, I'm also going to post my codes.
I'm not asking for codes from you, I just want to know, what I've done wrong and how I can fix it, any hints will be appreciated thanks
My Codes:
#include <iostream>
using namespace std;
const int maxx=100; //max 100 users
const int maxborrow=5; //maxx borrow books
int bi=0; //counter for books
int i=0; //counter for users
int number_of_customers=0;
//initialize numebr of users to 0
struct loanreserved
{
int loan; // 1 indicates true 0 indicates false if a book is reserved for example it's 1 if available 0
int reserved;
};
struct duedate
{
int day;
int month;
int year;
};
struct bookinf
{
char title[maxx];
char author[maxx];
int ISBN;
loanreserved loanorreserved;
duedate bookduedate;
};
struct userinf
{
char name[maxx];
char address[maxx];
int Id;
int number_of_reserved_books;
int number_of_loan_books;
bookinf customersbookinf[maxborrow];
};
userinf uniclibrary[maxx];
int readcustomer()
{
int uniqueid;
cout<<"Customer name: ";
cin>>uniclibrary[i].name;
cout<<"Customer address: ";
cin>>uniclibrary[i].address;
cout<<"Customer Id: ";
cin>>uniqueid; //save id to temp file;
for(int x=0;x<maxx;x++)
{
if(uniqueid!=uniclibrary[x].Id)
{
uniclibrary[i].Id=uniqueid;
cout<<"Customer registration succeeded ! \n";
number_of_customers++;
return 1; //success
}
}
cout<<"This user is already registered ! ";
return 0; //fail
system("pause");
system("cls");

You can have a static variable that keeps track of existing customers:
#include <set>
int readcustomer()
{
static std::set<std::string> existingNames;
std::string name;
cout<<"Customer name: ";
cin>>name;
if ( existingNames.find(name) != existingNames.end() )
{
//name already exists
return 0;
}
else
{
existingNames.insert(name);
}
//....
}
Of course, this is a quick fix. Better take your code to codereview. The're MUCH that can be improved.

Related

Error reading characters of string

I had a problem while trying to equal one string to another, I get this error "Error reading characters of string." in Visual Studio 2015, in the line that i am doing this "student_name=otherStudent.student_name;" and I just don't get it.
could you please help me?
Student& Student::operator=(const Student &otherStudent) {
if (this != &otherStudent) // Avoid self assignment
{
student_name=otherStudent.student_name;
for (int i = 0; i < grades_size; i++) {
grades[i] = otherStudent.grades[i];
subjet_names[i] = otherStudent.subjet_names[i];
}
average_grade = otherStudent.average_grade;
}
return *this;
}
Here is the definition of the class if it helps:
#include <iostream>
#include <string>
using namespace std;
#define grades_size 6
class Student {
private:
string student_name;
float grades[grades_size];
string subjet_names[grades_size];
float average_grade;
public:
//Constructor
Student();
Student(string name);
//Print status of Student
void printStudent();
//Operator Overloads
Student & operator=(const Student & otherStudent);
};

Displaying results in c++

I have a question concerning working with classes in c++. I must say I'm a beginner. For example, i have this class:
class student {
private:
char* name;
public:
int nrcrt;
student() {
name = new char[7];
name = "Anonim";
nrcrt = 0;
}
student(char* n, int n) {
this->name = new char[7];
strcpy(name, n);
nrcrt = nr;
}
~student() {
delete [] name;
}
char* get_name() {
return this->name;
}
}
void main() {
student group[3];
group[0] = student("Ana", 1);
group[1] = student("Alex", 2);
group[2] = student("Liam", 5);
for (i=0; i<3; i++) {
if (group.nrcrt[i] != 0)
cout << group[i].get_name() << Endl;
}
}
My question is why is it displaying different characters?
first of all your code is not working.
3.cpp:40:18: error: request for member ‘nrcrt’ in ‘group’, which is of non-class type ‘student [3]’
if(group.nrcrt[i]!=0)
i is also not declared.please make proper changes.
group.nrcrt[i]
should be changed to:
group[i].nrcrt
When the array is created, your default constructor is used.
When you assign to the elements, your destructor is called, deleting name.
The default constructor is assigning a literal to name, and deleting that memory has undefined behaviour.
In your default constructor, replace
name = "Anonim";
with
strcpy(name, "Anonim");
Your compiler should have warned you about the assignment.
If it didn't, increase the warning level of your compiler.
If it did, start listening to your compiler's warnings.
do not worry. C++ could look a bit scary as first but it is ok when you get into it. First, let's say that all classes it is good to start with upper case letters. Secondly, you have two constructors (default without parameters and one or more with, in our case one). Default consructor you need to declare an array of objects:
Student group[3];
The next important thing is that you then do not need the rest of the constructors in that case.
group[0]=student("Ana",1);
group[1]=student("Alex",2);
group[2]=student("Liam",5);
Remember to include ; at the end of class declaration. To put all the statements and expression throughout your interation within the same loop. Here is what I found as an errors anf fix them. Could probably have more.
class Student
{
private:
char* name;
public:
int nrcrt;
Student()
{
name=new char[7];
strcpy(name, "Anonim");
nrcrt=0;
}
Student( char* n, int n)
{
this->name=new char[7];
strcpy(name, n);
nrcrt=nr;
}
~Student()
{
delete [] name;
}
char* get_name()
{
return this->name;
}
};
int main()
{
Student group[3];
for(int i=0;i<3;i++)
{
if(group.nrcrt[i]!=0)
cout<<group[i].get_name()<<endl;
}
return 0;
}

FLTK Fl_Choice obtain selected item

I want to get the selected item of users but it gives an error on this code:
choice->value();
hopes you kind guys can help me.
Fl_Choice* choice;
int i = 0;
void but_cb(Fl_Button* obj, void*)
{
i = choice->value();
cout<<i;
}
int main (int argc, char* argv[]) {
Fl_Double_Window* win = new Fl_Double_Window(400,400,"Sample");
win->begin();
Fl_Choice* choice = new Fl_Choice(100,100,100,100,"Name");
choice->add("Peter");
choice->add("Tom");
choice->add("Mary");
Fl_Button* but = new Fl_Button(300,300,50,50,"Selected");
but->callback((Fl_Callback*)but_cb);
win->show();
return (Fl::run());
}
I did not spend much time reading the code, so the modified, and commented code below may not be solution to your problem. I believe choice is NULL in but_cb() as you are redefining choice in your main() function, hiding the global 'choice' pointer.
Fl_Choice* choice;
int i = 0;
void but_cb(Fl_Button* obj, void*) {
i = choice->value(); // uses global `choice` pointer to Fl_Choice.
cout << i;
}
int main (int argc, char* argv[]) {
Fl_Double_Window* win = new Fl_Double_Window(400,400,"Sample");
win->begin();
/* You are redefining choice here! BAD, because but_cb uses the global one.
Fl_Choice* choice = new Fl_Choice(100,100,100,100,"Name");
*/
// Good, assigns to the global `choice`, so it won't be NULL when but_cb is called
choice = new Fl_Choice(100,100,100,100,"Name");
choice->add("Peter");
choice->add("Tom");
choice->add("Mary");
Fl_Button* but = new Fl_Button(300,300,50,50,"Selected");
but->callback((Fl_Callback*)but_cb);
win->show();
return (Fl::run());
}

How to print n number of string in c?

#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
char *name;
int a;
name=(char *)malloc(sizeof(name));
printf("no. of names:");
scanf("%d",&a);
int i;
for(i=0;i<a;i++)
{
printf("enter the names:");
scanf("%s",name);
}
for(i=0;i<a;i++)
{
printf("entered names are:%s\n",name);
}
return 0;
free(name);
}
how to print n numbers of entered string in c am already asked this question but i dont got any proper answer any body known the answer please edit my code please if you run my code its displays last string only i dont know why please help..
You need an array of names. To achieve what you are trying to do you can use either a static array with the maximum size or allocate the memory dinamically as in the following program.
Note that you should also test the return value of malloc... just in case.
#include<stdio.h>
#include<string.h>
#include<malloc.h>
int main()
{
char **name;
int a;
printf("no. of names:");
scanf("%d",&a);
int i;
if( a<=0 )
return 0;
name = (char**)malloc( sizeof(char*)*a);
for(i=0;i<a;i++)
{
printf("enter the name:");
name[i]=(char*)malloc( sizeof(char)*128);
scanf("%s",name[i]);
}
for(i=0;i<a;i++)
{
printf("entered names are:%s\n",name[i]);
free(name[i]);
}
free(name);
return(0);
}
Note I had to cast malloc because the compiler that the OP is using raise the error " cannot convert from 'void ' to 'char ** ' " (which means that it's old enough..)
In
name=(char *)malloc(sizeof(name));
name is a char*, so sizeof(name) is the size of an address. Hence you are not allocating enough memory.
Just allocate more memory:
name=(char *)malloc(sizeof(char)*20); //allocating 20 bytes for the block that name will point tor
In addition to wrong space allocation (answered by brokenfoot), you will not get the results you want because you are reading all the names over and over in the same variable name, and later printing the name input last a times:
for(i=0;i<a;i++)
{
printf("enter the names:");
scanf("%s",name);
}
for(i=0;i<a;i++)
{
printf("entered names are:%s\n",name);
}
The right approach would be to use an array to store all the names, and later print them one by one. For example:
for(i=0;i<a;i++)
{
printf("Enter the names:")
scanf("%s",name[a]);
}
print("The entered names are: ");
for(i=0;i<a;i++)
{
printf("%s", name[a]);
}

Creating a 2 dimensional character array dynamically in C++

I want to create a 2 dimensional character array dynamically through pointers. Then input 10 strings in it and then take a string target from user and find it in array. if it is present then return its index. I have written code for it but it has errors. Please help me in correcting it. Thanks in advance.
#include<iostream>
#include<string>
using namespace std;
int strsearch(char [][50],char *);
int main()
{
char str[10][50];
char *target=new char [50];
int index;
for(int i=0; i<10; i++)
{
str = new char* [50];
str++;
}
for(int i=0; i<10; i++)
{
cout<<"Enter a sting";
cin>>str[i][50];
str++;
}
cout<<"Enter a string to find:";
cin>>target;
index=strsearch(str,target);
if(index<0)
{
cout<<"String not found";
}
else
{
cout<<"String exist at location "<<index<<endl;
}
return 0;
}
int strsearch(char string[10][50],char *fstr)
{
int slen;
for(int i=0;i<10;i++)
{
slen=strlen(**string);
if (strnicmp(*string[50],fstr,slen)== 0)
{
return i;
}
}
return -1;
}
Simply use:
std::vector<std::string> obj;
It will save you all the head & heart aches and guard you against easy to go wrong manual memory management issues. What you are trying to do is to solve the problem C way. With C++ the correct way to do it is using a vector of strings.
I think this is an error in any case:
for(int i=0;i<10;i++)
{
slen=strlen(**string);
if (strnicmp(*string[50],fstr,slen)== 0)
{
return i;
}
}
Must be something like:
for(int i=0;i<10;i++)
{
slen=strlen(string[i]);
if (strnicmp(string[i],fstr,slen)== 0)
{
return i;
}
}
I have done some correction, i think it can help you but i have not compiled to check for errors.
#include<iostream>
#include<string>
#define DIM_1 10 // Avoid to use "magic numbers" in your code
#define DIM_2 50
using namespace std;
int strsearch(char **string,char *fstr);
int main()
{
char **str = new char*[DIM_1]; //char str[10][50]; dynamically allocated array.
char *target=new char [DIM_2];
int index;
for(int i=0; i<DIM_1; i++)
{
str[i] = new char[DIM_2]; //Do not lost the original pointer
//str++;
}
for(int i=0; i<DIM_1; i++)
{
cout<<"Enter a sting";
cin>>str[i][DIM_2];
//str++; Do not lost the original pointer
}
cout<<"Enter a string to find:";
cin>>target;
index=strsearch(str,target);
if(index<0)
{
cout<<"String not found";
}
else
{
cout<<"String exist at location "<<index<<endl;
}
// Free memory!!
for (int i=0; i<DIM_1;i++) delete[] str[i];
delete[] str;
delete[] target;
return 0;
}
int strsearch(char **string,char *fstr) //its dinamicly allocated array
{
int slen;
int result=-1; //Only one return-> structured programming
for(int i=0;i<DIM_1;i++)
{
slen=strlen(**string);
//strlen and strnicmp is C, not C++, check string class.
if (strnicmp(string[i],fstr,DIM_2)== 0) //Find in the string[i]
{
result= i;
}
}
return result;
}

Resources