I have coded a program that gets the information of employees of a company, when I run it in Dec C++, it does run without any errors, but when I run it in Visual Studio, it returns the following error :
Error C4703 potentially uninitialized local pointer variable 'data' used
and VS asks me to rewrite the pointer like this :
employ *data{};
instaed of : employ *data;
Can anyone please explain why does it happen? and What this {} means here? Is it a thing of C++ or VS?
#include <iostream>
using namespace std;
struct employ {
long int emp_num;
string fn;
string ln;
int work_days;
long int payday;
};
int main()
{
int n=0;
employ *data;
int act;
do {
cout << "___________________________________________________________________________________________________________";
cout << "\n\n\t\tWelcome to the EMPLOTASK!";
cout << "\n\t\tFor doing any of the commands, enter number of that command.";
cout << "\n\t\t_______________________________________________________________";
cout << "\n\n\t\t\ ADD & EDIT : ";
cout << "\n\t\t[1] Add new employees.";
cout << "\n\t\t[2] Edit an existing employee.";
cout << "\n\t\t[3] Delete an existing employee.";
cout << "\n\t\t[4] Print list of all employees.";
cout << "\n\t\t_______________________________________________________________";
cout << "\n\n\t\t\ ACTIONS : ";
cout << "\n\t\t[5] Sort based on their salary.";
cout << "\n\t\t[6] Search for an emplyee.";
cout << "\n\t\t[7] Calculate the average salary.";
cout << "\n\t\t[8] Show maximum and minimum sallary.";
cout << "\n\n\t\tWhat do you want to do?";
cin >> act;
if (act > 8)
cout << "Invalid request!" << endl;
switch (act)
{
case 1: {
cout << "\n\t\t_______________________________________________________________";
cout << "\n\n\t\t\'ADD NEW EMPLOYEES\'";
cout << "\n\t\tEnter number of the employees : ";
cin >> n;
data = new employ[n];
for (int i = 0; i < n; i++)
{
cout << "\n\t\t========== Employee number " << i + 1 << " ==========";
cout << "\n\t\tFirst name : ";
cin >> data[i].fn;
cout << "\t\tLast name : ";
cin >> data[i].ln;
cout << "\t\tEmployee's number : ";
cin >> data[i].emp_num;
cout << "\t\tDays of work : ";
cin >> data[i].work_days;
cout << "\t\tDaily rate : ";
cin >> data[i].payday;
}
cout << "\n\t\t=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=";
cout << "\n\t\tOperatuon's done successfully! =)";
cout << "\n\t\t=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" << endl;
break;
}
case 2: {
cout << "\n\t\t_______________________________________________________________";
cout << "\n\n\t\t\'EDIT AN EMPLOYEE\'";
cout << "\n\t\tEnter the employee number : ";
int em_num;
cin >> em_num;
int yes = 0;
if (n == 0)
{
cout << "There's no employee!";
}
for (int i = 0; i < n; i++)
{
if (em_num == data[i].emp_num)
{
for (int j = 0; j < n; j++)
{
cout << "\n\t\t========== Edit Employee number " << i + 1 << " ==========";
cout << "\n\t\tFirst name : ";
cin >> data[i].fn;
cout << "\t\tLast name : ";
cin >> data[i].ln;
cout << "\t\tEmployee's number : ";
cin >> data[i].emp_num;
cout << "\t\tDays of work : ";
cin >> data[i].work_days;
cout << "\t\tDaily rate : ";
cin >> data[i].payday;
yes++;
}
}
}
if (yes == 0)
{
cout << "The entered employee number is invalid.";
}
break;
}
default:
break;
}
} while (act != 0);
return 0;
}
Regarding {}: uniform initialization(C++11). It enables you to initialize everything in the same way. It also provides better safety guarantees when it comes to narrowing conversions.
The following code shows some examples.
#include <iostream>
#include <string>
#include <vector>
struct Point
{
Point(float x, float y) : m_x{ x }, m_y{ y } {}
float m_x;
float m_y;
};
int main()
{
int a{ 0 }; // same as a{}
int b{ 1 };
// int c{ 2.0 }; // at least warning, often error
double d{ 3.0 };
char* pc{nullptr}; // same as pc{}
std::string s{ "C++" };
std::vector<int> vi{1, 2, 3, 4, 5};
Point p1{ 3.0f, 4.0f };
}
Related
The search function should get a value from the user to search for it, if the value is found, then it should print it out, and if not found it should print not found.
However, in my code every time I write the number that is in the array is gives me the false option although it is in the array stored.
`
#include <iostream>
using namespace std;
const int size = 100;
int partsmenu(int menu_option);
void readparts(char part_number[][10], double price[], char classification[], int& number_of_parts);
int search(char part_number[][10], char search_target[], int number_of_parts, double price[], char classification []);
void display_parts(char part_number[][10], double price[], char classification[], int& number_of_parts);
int main()
{
const int size = 100;
int menu_option=0, option, displaysearch;
char part_number[size][10];
double price[size];
char classification[size];
int number_of_parts = 0;
char search_target[size];
//using switch statment to make it look like a menu option
do {
switch (option = partsmenu(menu_option))
{
case 1:
readparts(part_number, price, classification, number_of_parts);
break;
case 2:
display_parts(part_number, price, classification, number_of_parts);
break;
case 3:
displaysearch = search(part_number, search_target, number_of_parts, price, classification);
break;
case 4:
break;
default:
cout << "Not valid..." << endl;
break;
}
cout << endl;
} while (option != 4);
return 0;
}
int partsmenu(int menu_option)
{
cout <<"1) Enter new part number\n2) View all part numbers\n3) Search for part\n4) Exit\n\nEnter an option: ";
cin >> menu_option;
return menu_option;
}
void readparts(char part_number[][10], double price[], char classification[], int& number_of_parts)
{
// using for loop to store part number, price, and classification in the array
int number;
cout << "Enter number of parts to add:";
cin >> number;
cout << endl;
int i;
for (i = number_of_parts; i < (number_of_parts+number); i++)
{
cout << "Enter part number: ";
cin >> part_number[i];
cout << "Enter price: ";
cin >> price[i];
cout << "Enter classificarion: ";
cin >> classification[i];
//using if statment to check for the classificarion
if (classification[i] == 'A' || classification[i] == 'B' || classification[i] == 'C')
cout << "";
else
{
cout << "Invalid case..." << endl;
cout << "Enter Valid class [A, B, C]: ";
cin >> classification[i];
cout << endl;
}
cout << endl;
}
number_of_parts = i;
}
int search(char part_number[][10], char search_target[], int number_of_parts, double price[], char classification[])
{
//searching for specific data
bool found = false;
int value;
cout << "Enter part number: ";
for (int j = 0; j < number_of_parts; j++)
{
cin >> search_target;
for (int i = 0; i < number_of_parts && found == false; i++)
{
if (part_number[i] == search_target)
found = true;
value = i;
}
}
if (found == true)
{
for (int i = 0; i < number_of_parts; i++)
{
cout << "Part ID\t\tPrice\t\tClass" << endl;
cout << " --------------------------------------------" << endl;
cout << part_number[value] << "\t\t" <<price[value]<< "\t\t" <<classification[value]<< endl;
}
}
else
{
cout << "No parts found..." << endl;
value = -1;
}
return value;
}
void display_parts(char part_number[][10], double price[], char classification[], int& number_of_parts)
{
// displaying the data
cout << "Part ID\t\tPrice\t\tClass" << endl;
cout << "--------------------------------------------" << endl;
for (int i = 0; i < number_of_parts; i++)
{
cout << part_number[i] << "\t\t" << price[i] << "\t\t" << classification[i] << endl;
}
cout << endl;
}
`
I am trying to find what is wrong with code but could not find any fault with it. Everything else works fine.
You compare C strings with strcmp not ==. Like this
if (strcmp(part_number[i], search_target) == 0)
If you use == then all you are comparing is the addresses of the strings, the addresses of two strings can be different even if the string contents are the same.
strcmp compares the actual characters in the strings, not the addresses. It returns 0 if the two strings are the same.
I am not sure how to connect a part of an array or if it is even possible.
My code is as follows:
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
string name;
string date[3];
double height[3];
double enter;
cout << "Enter name of a pole vaulter: ";
cin >> name;
cout << "Enter date of first vault: ";
cin >> date[0];
cout << "Enter height of first vault: ";
cin >> enter;
if (enter >= 2.0)
{
if (enter <= 5.0)
{
height[0] = enter;
}
else
{
cout << "Incorrect Value";
abort();
}
}
else
{
cout << "Incorrect Value";
abort();
}
cout << "Enter date of second vault: ";
cin >> date[1];
cout << "Enter height of second vault: ";
cin >> enter;
if (enter >= 2.0)
{
if (enter <= 5.0)
{
height[1] = enter;
}
else
{
cout << "Incorrect Value";
abort();
}
}
else
{
cout << "Incorrect Value";
abort();
}
cout << "Enter date of third vault: ";
cin >> date[2];
cout << "Enter height of third vault: ";
cin >> enter;
if (enter >= 2.0)
{
if (enter <= 5.0)
{
height[2] = enter;
}
else
{
cout << "Incorrect Value";
abort();
}
}
else
{
cout << "Incorrect Value";
abort();
}
int len = sizeof(height) / sizeof(height[0]);
sort(height, height + len, greater<int>());
cout << "Stats for " << name << ":" << endl;
for (int i = 0; i < len; i++) {
cout << height[i] << " ";
}
cout << height[0];
}
I am trying to enter dates and a double value, and then organize the double values in descending order and keep the dates with the corresponding value. I am not sure if this is possible, any alternative way of completing this would be helpful.
Thank you
Group of data, data sorting, multiple data points that should be aligned/connected to their respective other data points. I think the best solution here would be the use of a struct or class with vectors:
Let's say you want a variable that contains both your date and number. We can construct a class or structure for that:
#include <iostream>
using namespace std;
struct str1
{
string date;
double number;
};
class cls1
{
public:
string date;
double number;
};
int main()
{
str1 ob1;
cls1 ob2;
ob1.date = "somedate";
ob1.number = 12345;
cin >> ob1.date;
cout << ob1.date << " " << ob1.number << endl;
ob2.date = "somedate2";
ob2.number = 54321;
cin >> ob2.number;
cout << ob2.date << " " << ob2.number << endl;
return 0;
}
Having a class or struct enables you to use objects (variables made from those structs or classes). Every object created has their own place in memory for storing both date and number. You can use, find, search any of these variables and have access to both values this way.
Grouping them up so there's a list of them can be done in vectors.
Vectors are like better arrays. They not only have a dynamical size (meaning its size can change and doesnt stay static like in arrays), but they also have quite a bit ready made functions for you to use:
bool sortingFunction(int &a, int &b)
{
if (a > b) return true;
else return false;
}
int main2()
{
vector<int> numbers;
//to add
numbers.emplace_back(5); //5 is the number to add
//to remove
numbers.erase(numbers.begin() + 2); //2 is the index of the variable to delete
//to sort
sort(numbers.begin(), numbers.end(), sortingFunction);
return 0;
}
Vectors need the #include <vector> header.
Sort is a function that sorts. Needs #include <algorithm> header.
Sort function is neat because you can define the logic behind how you want to sort the vector or array with a seperate function that returns either true or false.
For your example you could do something like this in the end:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct myType
{
string date;
double number;
};
bool sortByDate(myType &a, myType &b)
{
if (a.date > b.date) return true;
else return false;
}
bool sortByNumber(myType &a, myType &b)
{
if (a.number > b.number) return true;
else return false;
}
int main()
{
vector<myType> variables;
int num;
cout << "how many do you want to add" << endl;
cin >> num;
for(int i = 0; i < num; i++)
{
myType tmp;
cout << "Enter date of var" << i+1 << ": ";
cin >> tmp.date;
cout << "Enter number of var" << i+1 << ": ";
cin >> tmp.number;
variables.emplace_back(tmp);
}
//after that you can use the vector as you want...
//sort
sort(variables.begin(), variables.end(), sortByDate);
sort(variables.begin(), variables.end(), sortByNumber);
//delete
variables.erase(variables.begin()+5);
//or clear the entire thing
variables.clear();
//Either way each item in the vector consists of both number and date thus even
//if you sort the vector the values are still connected at the same position
return 0;
}
I am getting this error every time I try to run my program.
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
terminate called after throwing an instance of
'std::logic_error' what(): basic_string::_M_construct null not valid
#include <iostream>
#include <string>
using namespace std;
struct Bin
{
string desc;
int partsQty;
};
void addParts(Bin bList[], int i);
void removeParts(Bin bList[], int i);
int main() {
char response;
int binNumber;
const int NUM_OF_BINS = 11;
Bin binList[NUM_OF_BINS] = {
{0,0},
{"Valve", 10},
{"Earing",5},
{"Bushing",15},
{"Coupling",21},
{"Flange",7},
{"Gear",5},
{"Gear Housing",5},
{"Vaccum Gripper",25},
{"Cable",18},
{"Rod",12}
};
for(int i=1;i < 11;i++)
{
cout << "Bin #" << i << " Part: " << binList[i].desc << " Quantity " << binList[i].partsQty << endl;
}
cout << "Please select a bin or enter 0 to terminate";
cin >> binNumber;
cout << "Would you like to add or remove parts from a certain bin?(A or R)";
cin >> response;
if(response == 'a')
addParts(binList, binNumber);
else if(response == 'r')
removeParts(binList, binNumber);
return 0;
}
void addParts(Bin bList[], int i)
{
int parts;
int num;
cout << "How many parts would you like to add?";
cin >> num;
parts = bList[i].partsQty + num;
cout << "Bin # " << i << " now contains " << parts << " parts";
}
void removeParts(Bin bList[], int i)
{
int parts;
int number;
cout << "Which bin would you like to remove parts to?";
cin >> i;
cout << "How many parts would you like to remove?" << endl;
cin >> number;
parts = bList[i].partsQty - number;
if(parts < 0)
cout << "Please enter a number that isn't going to make the amount of parts in the bin negative.";
cin >> number;
parts = bList[i].partsQty - number;
cout << "The remaining amount of parts in bin #" << i << " is " << parts;
}
It comes from:
{0,0}
in your list of initializers for binList. 0 is not a correct initializer for std::string. You could perhaps use {"", 0} instead, or even {}.
Another idea might be to revise your program logic so that you do not require a dummy entry at the start of the array.
This question already has answers here:
Using fstream Object as a Function Parameter
(3 answers)
Closed 6 years ago.
#include <bits/stdc++.h>
using namespace std;
class contact {
private:
vector< pair<string, int> > contact_info;
public:
void add_contact(string contact_name, int contact_number) {
contact_info.push_back(make_pair(contact_name, contact_number));
sort(contact_info.begin(),contact_info.end());
}
void edit_contact(string contact_name) {
int found_at;
for (unsigned int i =0; i < contact_info.size(); i++) {
if (contact_info[i].first == contact_name) {
found_at = i;
}
}
if (contact_info[found_at +1].first == contact_name) {
int choice;
int counter = found_at;
int index = 1;
while (contact_info[counter].first == contact_name) {
cout << index << ". " << contact_info[counter].first << " " << contact_info[counter].second;
counter++;
index++;
}
cout << "Choose any please: ";
cin >> choice;
found_at = found_at - (choice - 1);
}
cout << "Enter the new number: ";
cin >> contact_info[found_at].second;
}
void show_all() {
for (unsigned int i =0; i < contact_info.size(); i++) {
cout << contact_info[i].first << " " << contact_info[i].second << endl;
}
}
void delete_contact(string contact_name) {
int found_at;
for (unsigned int i =0; i < contact_info.size(); i++) {
if (contact_info[i].first == contact_name) {
found_at = i;
}
}
if (contact_info[found_at +1].first == contact_name) {
int choice;
int counter = found_at;
int index = 1;
while (contact_info[counter].first == contact_name) {
cout << index << ". " << contact_info[counter].first << " " << contact_info[counter].second;
counter++;
index++;
}
cout << "Choose any please: ";
cin >> choice;
found_at = found_at - (choice - 1);
}
contact_info.erase(contact_info.begin()+found_at);
}
void writeFile(ofstream contact_file) {
for (unsigned int i =0; i < contact_info.size(); i++) {
contact_file << contact_info[i].first << " " << contact_info[i].second << endl;
}
}
void readFile(ifstream contact_file) {
string input;
while (!contact_file.eof()) {
contact_file >> input;
size_t pos = input.find(" ");
string name = input.substr(0,pos);
string number_str = input.substr(pos);
int number = stoi(number_str) ;
contact_info.push_back(make_pair(name,number));
}
}
};
int main()
{
int choice;
ifstream contacts_file_read;
contacts_file_read.open("contacts.txt");
ofstream contacts_file_write;
contacts_file_write.open("contacts.txt");
bool in_prog = true;
contact contacts;
string name;
int number;
while (in_prog) {
cout << "1. Add contacts" << endl
<< "2. Edit contact" << endl
<< "3. Delete contact" << endl
<< "4. Show all" << endl
<< "5. exit" << endl;
cout << "Your choice: ";
cin >> choice;
contacts.readFile(contacts_file_read);
if (choice == 1) {
cout << "Enter name & number separated by a space: ";
cin >> name >> number;
contacts.add_contact(name, number);
} else if (choice == 2) {
cout << "Enter name of contacts to be edited: ";
cin >> name;
contacts.edit_contact(name);
} else if (choice == 3) {
cout << "Enter name of contact to be deleted: ";
cin >> name;
contacts.delete_contact(name);
} else if (choice == 4) {
contacts.show_all();
} else if(choice == 5) {
contacts.writeFile(contacts_file_write);
} else {
cout << "Wrong choice" << endl;
}
}
return 0;
}
So, I was asked in my programming class to make a phone book application in C++ using only objects, so this is my attempt at it.
All functions are good, I did recompile the program after finishing each function at it gave me 0 errors, however whenever I try to call writeFile or readFile function that were previously working fine, now the compiler gave me an error of "error: use of deleted functions... "
I don't know what are deleted functions and why only functions that take file objects as an argument are treated as such.
Can anyone please help?
Thanks.
Objects of type std::ifstream are not copyable -- indeed, the object represents the unique handle of an open file, and it would be difficult to conceptualize what it would mean to copy such unique responsibility.
Indeed, this inability to copy an object is encoded by making the copy constructor deleted, which causes the error that you see when you do attempt to copy it.
Your code should pass the original ifstream, not a copy (by taking a reference parameter):
void readFile(ifstream & contact_file)
// ^^^^^^^^^^
I've come across a little problem, how do I print the winning candidate's name? See the instructions here are, input five names, their number of votes and percentage of votes, whoever has the highest wins. I don't know if I did my code right, but it works.. well except for the name part. I've tried everything from a lot of for loops to transfer the array or what.
I'm almost done with the code.
Here's the code
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
char candidates[50];
int votes[5]={0};
float percent[5]={0};
int a,b,c,d,e,i;
int maxx;
int champ=0;
char winner[50];
cout << "Enter the candidates' last names: ";
cout << endl;
for(a=1;a<=5;a++)
{
cout << a << ". ";
cin >> candidates;
}
cout << endl;
cout << "Enter their number of votes: " << endl;
for(b=1;b<=5;b++)
{
cout << b << ". ";
cin >> votes[b];
}
cout << endl;
cout << "percentage of votes: " << endl;
for(c=1;c<=5;c++)
{
cout << c << ". ";
percent[c]=votes[c]*0.2;
printf("%.2f\n", percent[c]);
}
cout <<"Candidates\t\tVotes\t\t% of Votes" << endl;
for(int k=1;k<=5;k++)
{
cout << candidates[k] << "\t\t\t" << votes[k] << "\t\t\t";
printf("%.2f\n", percent[k]);
}
maxx=percent[0];
for(d=1;d<=5;d++)
{
if(maxx<percent[d]);
{
//what happens here?
}
}
return 0;
}
You should keep a 2d array of characters or array of string for storing candidate names instead of a 1-d array.
char candidates[5][10]; //
for(int i = 0; i < 5; i++)
{
cin >> candidates[i];
}
Then keep a variable to store index for winning candidate
int winIndex = 0;
int winPercent = 0;
for(int i = 0; i < 5; i++)
{
if(percent[i] > winPercent)
{
winPercent = percent;
winIndex = i;
}
}
Finally print name of winning candidate;
cout << candidates[winIndex];
In object oriented approach, you may create a class with following information
class Candidate
{
string name;
int votes;
float percent;
};
Use string candidates[50]; instead of char candidates[50];
then cin >> candidates[a];