I am newbie into programming and have this c++ school quizzes.
I wanted to push entered arrays elements to the right.
here is my existing code
Blockquote
// automatac++.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <list>
#include <iterator>
#include <conio.h>
#include <cstring>
//using namespace std;
using std::cout;
using std::cin;
using std::endl;
void menu_sel();
void push_element();
//void rem_element();
int in;
char array[100];
int p_elements;
int main()
{
menu_sel();
return 0;
}
void push_element() {
int p_elements;
for (int e = 0; e < 10; e++) {
}
cout << "Enter number of elements:";
cin >> p_elements;
cout << "Enter only " << p_elements << " elements"<<endl;
for (int e = 0; e < p_elements; e++ ) {
cin >> array[e];
}
cout << "Pushed elements are :";
for (int e = 0; e < p_elements; ++e) {
cout << array[e]<<" ";
}
//getch();
menu_sel();
}
/*
void rem_element() {
char remove;
int arr_position;
cout << "You have selected Pop.\nRemove elements from arrays \n";
cout << "Enter data to remove";
cin >>remove;
for (int ie -) {
}
system("pause");
}
*/
void menu_sel() {
int input;
cout << "\n****Menu Selection Here****";
cout << "\n1. Push \n2. Pop \n3. Exit \n";
cout << "select options here :";
cin >> input;
switch (input) {
case 1:
cout << "You have selected Push Stack\n";
push_element();
break;
case 2:
//cout << "You have selected Pop Stack\n";
//rem_element();
break;
default:
cout << "You have selected Invalid Options";
break;
system("cls");
return;
}
}
and here is the output
the output shows pushing elements to the left
the output was 3 e r 4
I wanted to shows output like this "4 r e 3"
thanks and regards,
You can always read your array backwards for output if you want to show it that way.
for (int e = p_elements-1; e >= 0; --e) {
cout << array[e]<<" ";
}
Related
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 };
}
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'm working on a program that I've seen other people do online except I'm trying to use functions to complete it to make it somewhat more challenging for me to help me better understand pointers and vectors. The problem I'm having in xcode is I keep getting this error..
Expected ';' after top level declarator
right here on my code,
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers) //<<< Error
{
cout << fixed << setprecision(2);
...
Where I am trying to use vector numbers in my function. Basically I want the numbers from the function passed back so that I can use them in another function I have not created yet. I've googled this error and it seems like no one can give a straight answer on how to fix this problem. Is anyone familiar with how to correct this? By no means is this code finished I'm just trying to get information regarding vectors as a parameter because from what I'm seeing syntax wise on other sites it looks to be correct. Thanks for your feedback.
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>
#include <iterator>
using namespace std;
struct menuItemType{
string menuItem;
double menuPrice;
};
void getData(menuItemType (&mlist)[8]);
void showMenu(menuItemType (&menu_List)[8], vector<int> numbers);
int main() {
vector<int> temp;
menuItemType menuList[8];
getData(menuList);
showMenu(menuList,temp);
/*
cout << menuList[0].menuItem << " " << menuList[0].menuPrice << endl;
cout << menuList[1].menuItem << " " << menuList[1].menuPrice << endl;
*/
return 0;
}
void getData(menuItemType (&mlist)[8]){
string Str;
ifstream infile;
infile.open("cafe135.txt");
if(infile.is_open())
{
for (int i = 0; i < 8; ++i){
infile >> mlist[i].menuItem >> mlist[i].menuPrice;
}
}
else cout << "Unable to open file";
}
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers)
{
cout << fixed << setprecision(2);
string choice;
cout << "Would you like to view the menu? [Y] or [N]: ";
cin >> choice;
cout << endl;
int x = 3;
int count = 1;
while (choice != "Y" && choice != "N" && choice != "y" && choice != "n")
{
if (count == 4){
return;
}
cout << "Error! Please try again ["
<< x
<< "] selections remaining: ";
cin >> choice;
cout << endl;
x--;
count++;
}
if (choice == "N" || choice == "n"){
return;
}
else
{
cout << "___________ Breakfast Menu ___________" << endl;
for (int i = 0; i < sizeof(menu_List)/sizeof(menu_List[0]); ++i)
{
cout << "Item "
<< (i+1)
<< ": "
<< menu_List[i].menuItem
<< " "
<< menu_List[i].menuPrice
<< endl;
}
cout << endl;
string itemSelection = " ";
//int str_length = 0;
cout << "Select your item numbers separated"
<< " by spaces (e.g. 1 3 5) Select 0 to cancel order: ";
cin.ignore();
getline(cin, itemSelection);
if (itemSelection == "0")
{
return;
}
vector<int> vectorItemSelection;
stringstream text_stream(itemSelection);
string item;
while (getline(text_stream, item, ' '))
{
vectorItemSelection.push_back(stoi(item));
}
int n = vectorItemSelection.size();
int arr[n];
for (int i = 0; i < n; i++)
{
arr[i] = vectorItemSelection[i];
}
}
}
Compare how menu_List is declared in this line
void showMenu(menuItemType (&menu_List)[8], vector<int> numbers);
and this line
void showMenu(menuItemType (&menu_List)[8])[], vector<int> numbers)
The first one is correct.
But I have to agree with the comments above, you are mixing up a lot of different things here. Just use vectors, 99% of the time it's the right thing to do anyway. and it's easier to learn one thing at a time.
Prefer to write your code like this
void getData(vector<menuItemType>&);
void showMenu(vector<menuItemType>&, vector<int> numbers);
int main() {
vector<int> temp;
vector<menuItemType> menuList(8);
...
See? Just use vectors everywhere.
I cannot figure out why my getchar() function is not working the way I want it to work. I am getting 10 not 2. Please take a look.
Main():
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int var, newvar;
cout << "enter a number:" << endl;
cin >> var;
newvar = getchar();
cout << newvar;
return 0;
}
Here is my output:
enter a number:
220
10
Ultimately though I need to be able to distinguish between a '+' '-' or letter or number.
This is maybe not the cleanest way to do it but you can get every char one by one :
#include <iostream>
using namespace std;
int main()
{
int var;
cout << "enter a number:" << endl;
cin >> var;
std::string str = to_string(var);
for(int i=0; i < str.length();++i)
cout << str.c_str()[i] << endl;
return 0;
}
If you enter for example: "250e5" it will get only 250 and skip the last 5.
Edit:
This is just a simple parser and does not do any logic.
If you want to make a calculator I would recommend you to look at what Stroustrup did in his book the c++ programming language.
int main()
{
string str;
cout << "enter a number:" << endl;
cin >> str;
for(int i=0; i < str.length();++i) {
char c = str.c_str()[i];
if(c >= '0' && c <= '9') {
int number = c - '0';
cout << number << endl;
}
else if(c == '+') {
// do what you want with +
cout << "got a +" << endl;
} else if(c == '-')
{
// do what you want with -
cout << "got a -" << endl;
}
}
return 0;
}
what i am trying to do is display my pointer to an array of objects. here is my main program, the function it crashes at is listAll(). if i only enter one object it works, but when i enter a second one it crashes. i am at a loss of what is going wrong. problem occurs after picking menuOption 1 twice and then trying to call list all. i see that the array size is not being increased..
#include <fstream>
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
#include "fileStuff.h"
bool menu();
bool menuOptions(int option);
void fileIO();
void listAll(interact * obs, int arryO);
int main()
{
bool isRunning = true;
while (isRunning)
{
isRunning = menu();
}
return 0;
}
bool menu()
{
int option = 0;
cout << "1: add new backpack. " << endl
<< "2: delete a backpack "<< endl
<< "3: sort ascending by id " << endl
<< "4: sort descending by id " << endl
<< "5: list all backpacks " << endl
<< "6: quit" << endl;
cin >> option;
return menuOptions(option);
}
bool menuOptions(int option)
{
static int arrayO = 0;
static interact *obs = new interact[arrayO];
fileStuff test;
int tempBagId = 0, tempInvSpaces = 0, tempAmtOfItemsInInv = 0;
double tempInvMaxWeight = 0.0;
string tempBagType, tempBagCondish;
int t = 0 ;
int i = 0;
switch (option)
{
case 1:
cout << "bagId? ";
cin >> tempBagId;
cout << "How many inv spaces? ";
cin >> tempInvSpaces;
cout << "How much weight can the bag hold? ";
cin >> tempInvMaxWeight;
(obs + arrayO)->setBagId(tempBagId);
(obs + arrayO)->setInvSpaces(tempInvSpaces);
(obs + arrayO)->setInvMaxWeight(tempInvMaxWeight);
cout << "all stored" << endl;
arrayO++;
break;
case 2:
//listmanager delete one
//arrayO--;
break;
case 3:
//sort ascending by id
break;
case 4:
//sort descending by id
break;
case 5:
//list all
listAll(obs, arrayO);
break;
case 6:
obs = NULL;
delete obs;
return false;
break;
default:
break;
}
}
void listAll(interact * obs, int arryO)
{
int i = 0;
cout << i << endl;
cout << arryO << endl;
}
below is the gists of my class.
#include "listManager.h"
#include <iostream>
#include <string>
using namespace std;
interact::interact()
{
bagId = 0;
invSpaces = 0;
invMaxWeigt = 0;
}
void interact::setBagId(int id)
{
bagId = id;
}
void interact::setInvSpaces(int spaces)
{
invSpaces = spaces;
}
void interact::setInvMaxWeight(double weight)
{
invMaxWeigt = weight;
}
int interact::getBagId()
{
return bagId;
}
int interact::getInvSpaces()
{
return invSpaces;
}
double interact::getInvMaxWeight()
{
return invMaxWeigt;
}
You have:
static int arrayO = 0;
static interact *obs = new interact[arrayO];
This will create a dynamic array of 0 length. As Ben stated, the pointer will never change.
The crash is probably caused by trying to access it after increasing the index (arrayO++;), after that it will just be accessing out of bounds memory.
Your obs points to an array with size zero:
static int arrayO = 0;
static interact *obs = new interact[arrayO];
and never is changed to point to anything larger.
Therefore every attempt to subscript it is an array overrun.