Here is the code:
void option5 (StudentRecord student[], int n)
{
double gpaThreshold;
char enteredMajor;
int i;
cout << "Enter a GPA threshold: ";
cin >> gpaThreshold;
cin.ignore(80, '\n');
cout << "Enter a Major: ";
cin >> enteredMajor;
cin.ignore(80, '\n');
enteredMajor = toupper(enteredMajor);
for (i = 0; i < n; i++)
{
if (student[i].gpa >= gpaThreshold && student[i].major == enteredMajor)
{
if (i % 10 == 0)
{
cin.ignore();
}
cout << setw(3) << right << i+1 << ". "
<< setw(20) << left << student[i].lastName
<< setw(20) << left << student[i].firstName
<< setw(8) << left << student[i].major
<< fixed << setprecision(2) << setw(8) << left << student[i].earnedHours
<< fixed << setprecision(2) << setw(6) << left << student[i].gpa << endl;
}
}
}
StudentRecord is a struct, and the only integer on that line is 'i', whereas the pointer (I would have to assume) is .major.
I'm wanting to compare an entered major, with the "Major" values in the array.
E.G. I type in Chem
-turns to CHEM
-fetches all students under that major (and threshold of GPA)
-displays the above statement (all students of 'X' major)
Any suggestions? Help? Comments? Positive/Negative Feedback?
EDIT: Here is the struct:
struct StudentRecord
{
char lastName [16]; // field definitions of the structure
char firstName[16];
char hometown [16];
char major[5];
int studentNumber;
double balance;
int earnedHours;
double gpa;
};
Consider this fragment:
student[i].major == enteredMajor
student[i].major is a char[5], which devolves into a char* in this context. This is a pointer type.
enteredMajor is a char. This is an integral type.
You cannot compare these types.
Perhaps you meant to decalre enteredMajor thus:
char enteredMajor[5];
and compare them like this:
strcmp(student[i].major, enteredMajor) == 0
student[i].major is a char array; when used in an expression it decays into a pointer to char. The code compares it for equality with enteredMajor which has type char. Thus the complaint: can't compare a pointer and an integer (because char gets promoted to int).
Related
I'm having a bit of issues with a C++ Project that I'm working on for a class. I keep getting an error message stating 'no instance of overloaded function'. I did some googling and it seems that everyone says that this error is caused by passing a string into the cin.get() function, but I'm using this function with a char, not a string. Visual Studio says the error is at: "cin.get(nameFull);" but I've defined nameFull as a char, not a string. Any help would be greatly appreciated, thank you for your time.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int MONTHS = 12;
const int RETRO_MONTHS = 6;
char nameFull[30]; // INPUT - Employee's full name
float salaryCurrent; // INPUT - Current annual salary
float percentIncrease; // INPUT - Percent increase due
float salaryNew; // OUTPUT - New salary after increase
float salaryMonthly; // OUTPUT - New monthly salary
float retroactivePay; // OUTPUT - Retroactive pay due employee
int count; // CALC - Counter for loop
for (int count = 0; count < 3; count++) {
cout << "What is your name?" << endl;
cin.get(nameFull);
cout << "What is your current salary?" << endl;
cin >> salaryCurrent;
cout << "What is your pay increase?" << endl;
cin >> percentIncrease;
salaryNew = salaryCurrent + (salaryCurrent * percentIncrease);
salaryMonthly = salaryNew / MONTHS;
retroactivePay = (salaryNew - salaryCurrent) * RETRO_MONTHS;
cout << nameFull << "'s SALARY INFORMATION" << endl;
cout << "New Salary"
<< setw(20) << "Monthly Salary"
<< setw(20) << "Retroactive Pay" << endl;
cout << setprecision(2) << fixed << setw(10) << salaryNew
<< setw(20) << salaryMonthly
<< setw(20) << retroactivePay << endl;
cout << "<Press enter to continue>" << endl << endl;
cin.get();
}
return 0;
}
nameFull is an array of char (more specifically char[30]) which decays to a pointer to character (char*). There is no overload of std::istream::get which accepts a single pointer to character, but there is one that accepts a pointer + the size of the buffer that you would like to read into.
So all you need to do is pass an additional parameter:
cin.get(nameFull, 30);
This question already has answers here:
invalid conversion from 'int' to 'int*' [-fpermissive] on passing array
(3 answers)
Closed 4 years ago.
void drawTable(int arg[], int length);
int main()
{
int length=0;
int counter=0;
int *pointer2ArrSize = new int[length];
cout << "Enter length of array: " << endl;
cin >> length;
do{
for(int j=0; j<length; j++){
cout << "Enter array elements: \n";
cin >> pointer2ArrSize[j];
cout << "You entered: " << pointer2ArrSize[j] << " in position: "
<< j+1
<< endl;
counter++;
}
cout << drawTable(pointer2ArrSize[j],length) << endl;
}while(!counter == length);
return 0;
}
void drawTable(int arg[], int length){
for(int i=0; i<length; i++){
cout << arg[i] << " ";
cout << '/n';
}
}
error: invalid conversion from 'int' to 'int*' [-fpermissive]
My goal is to display a 2D variable length array. I want the user to define the length of the array and the elements in it. However, am not too familiar with vectors yet. how could I approach this?
cout << drawTable(pointer2ArrSize[j],length) << endl;
is wrong since the argument type for drawTable is int* and you are passing pointer2ArrSize[j] to it, which is of type int.
You need to use
cout << drawTable(pointer2ArrSize, length) << endl;
More importantly, use of
int *pointer2ArrSize = new int[length];
cout << "Enter length of array: " << endl;
cin >> length;
is wrong.
The array will not be resized to length after you accept its value from the user. Consequently, pointer2ArrSize will continue to be an array of size 0. Since pointer2ArrSize continues to be an array of size 0, any attempt to access its elements will result in undefined behavior.
Move the line that allocates memory after you have accepted the input value for length.
cout << "Enter length of array: " << endl;
cin >> length;
int *pointer2ArrSize = new int[length];
It will be better still to use std::vector. Then, you don't have to worry about memory allocation and deallocation.
cout << "Enter length of array: " << endl;
cin >> length;
std::vector<int> pointer2ArrSize(length);
Of course, you should change drawTable to accept a std::vector<int>.
void drawTable(std::vector<int> const& arg);
There won't be the need for length as a second argument to drawTable since you can get the size of the array from the std::vector.
This question already has answers here:
What are the basic rules and idioms for operator overloading?
(8 answers)
Closed 6 years ago.
#include <iostream>
#include <string>
using namespace std;
class sequence{
public:
sequence();
sequence(int x);
sequence& operator*=(const &left, const &right);
~sequence();
friend istream& operator >>(istream&, sequence&);
friend ostream& operator <<(ostream&, sequence&);
void set_num_samples(); //Set no. of samples
float* value; //pointer to float variable
void allocate_memory(); //Allocates memory
void set_values_array(); //Sets the values of an array
void check_array_input(float l); //Checks the values of the array
void reset_input(float j); //Resets the array
void de_allocate(); //deallocates memory
int get_num_samples();
void set_full_array(int x);
void calculate_full(float array1[], float array2[]);
void combine_seq_coef(sequence& inputvoltageA); //Combines the passed in sequence and coefficient
void combine_seq(sequence& objectcombine, int sample); // combine the sequences
private:
int num_samples; //number of samples in the object sequence
};
class FIR{
public:
FIR();
~FIR();
private:
int num_coefficients; //Number of coefficients in an FIR (filter impulse response)
};
//Constructor for each object
void sequence::set_num_samples() { //Set_num_sample definition
cout << "Please enter the number of values in your sequence: \n";
cin >> num_samples;
if(num_samples < 0){
cout << "Value entered must be greater than 0 "<< endl;
cout << "Please enter the value again: " << endl;
cin >> num_samples;
}
}; //ok (stream op)
void sequence::allocate_memory() {
value = new float[num_samples]; //Allocated memory for Array.
}; //ok
void sequence::set_values_array(){ //Set values for array
int k;
for(k=0; k<num_samples; k++){
cout << "Please enter a positive value for element : " << (k+1) << endl;
cin >> value[k];
while(value[k] < 0){
cout << "Enter positive value " << endl;
cin >> value[k];
}
}
cout << "Values have been assigned successfully! " << endl;
}; //ok
//Constructor functions
void sequence::check_array_input(float l) { //Checks array values.
cout << endl << "If you would like to check input values, enter 'y' otherwise, enter 'n' to continue..." << endl;
char check_value;
cin >> check_value;
if (check_value == 'y') {
int i;
for (i = 0; i < l; i++) {
cout << "Value no. " << (i + 1) << " is:" << endl;
cout << value[i] << endl;
}
}
}
void sequence::reset_input(float j) { //Reset voltage value and set to 0;
cout << endl << "If you would like to reset all input values, enter 'y' otherwise, enter 'n' to continue..."
<< endl;
char check_value2;
cin >> check_value2;
if (check_value2 == 'y') {
int i;
for (i = 0; i < j; i++) {
cout << "Value no." << (i + 1) << ": " << value[i];
value[i] = 0;
cout << " is set to 0!" << endl;
}
}
}
void sequence::de_allocate(){
delete[] value; //De-allocate memory
num_samples = 0;
cout << "De-allocation of input array successful, num of samples reset to 0! " << endl;
}
int sequence::get_num_samples(){
return num_samples;
}
/* void sequence::calculate_full(float array1[], float array2[]){
int loop;
for(loop=0; loop<num_samples; loop++){
cout << "CoefficientA value no: " << (loop+1) << ": " << array1[loop].value[loop] << endl;
cout << "InputvoltageA value no." << (loop+1) << ": " << array2[loop].value[loop] << endl;
value[loop] = (array1[loop].value[loop])*(array2[loop].value[loop]);
cout << "Combined value no. " << (i+1) << ": " << value[loop] << endl;
cout << "The combined value gives" << full[loop] << endl;
}
}; */
void sequence::set_full_array(int x){
num_samples = x;
}
void sequence::combine_seq(sequence& object_combine, int sample_num){
int loop;
for(loop=0; loop<sample_num; loop++){
}
};
sequence& sequence::operator*=(const &left, const &right){
int y = left.get_num_samples();
int x;
for (x=0; )
sequence = left.value * right.value
return sequence;
}
sequence::sequence(){ //SEQUENCE CONSTRUCTOR
set_num_samples();
allocate_memory();
set_values_array();
check_array_input(num_samples);
reset_input(num_samples);
de_allocate();
cout << endl << "Constructor complete!" << endl;
};
sequence::sequence(int a){ //sequence constructor 2
set_full_array(a);
allocate_memory();
}
/* sequence::sequence(int a){
set_full_samples();
allocate_memory();
int i;
for(i=0; i<num_samples; i++){
cout << "CoefficientA value no: " << (i+1) << ": " << coefficientA().value[i] << endl;
cout << "InputvoltageA value no." << (i+1) << ": " << inputvoltageA.value[i] << endl;
cout << "Combined value no. " << (i+1) << ": " << value[i] << endl;
}
}
*/
sequence::~sequence(){ //Destructor
cout << "Destructor is called" << endl;
}; //destructor
int main(){
// Create object, constructor called
// Constructor calls, set_num_sample, allocate_memory, set_values_array
// Enters values for voltage Inputs to the sequence into an array
// Checks values of the array
// Asks user if they want to reset values and set num samples = 0.
do {
cout << "Press the Enter key to continue:" << endl;
} while (cin.get() != '\n');
cout << "Input voltage sequence created!" << endl;
sequence inputvoltageA;
cout << endl << "CoefficientA sequence created!" << endl;
sequence coefficientA;
//Combines sequence and coefficients
cout << "If you would like to combine the coefficients with the input sequence A enter 'y', otherwise enter 'n'" << endl;
char prompt4;
cin >> prompt4;
if(prompt4 == 'y'){
int x = coefficientA.get_num_samples();
sequence full(x);
full = coefficientA*inputvoltageA;
}
/* Ask the user if they want to create new object
cout << "If you would like to create a new input voltage sequence enter 'y', otherwise enter 'n'" << endl;
char prompt3;
cin >> prompt3;
if(prompt3 == 'y'){
sequence inputvoltageB;
}
cout << "CoefficientA sequence created!" << endl;
sequence coefficientB;
*/
/*
cout << "If you would like to combine this sequence with the sequence before enter 'y', otherwise enter 'n'" << endl;
char prompt5;
cin >> prompt5;
if(prompt5 == 'y'){
combine_seq(inputvoltageA, num_samples);
} */
return 0;
}
Why cant i overload the * operator?
The compiler gives me the error c++ must have a type specifier.
My type specifier is a reference to a sequence object...
I think ive defined the overload operator * function correctly in the class and outside of it.
You're overloading operator*= not operator*. operator*= is a binary operator - you either need to:
define it as a friend binary function inside the class body;
friend auto& operator*=(sequence& l, sequence& r) { /* ... */ }
define it as a non-friend unary function inside the class body (where the left-hand side is implicitly *this);
auto& operator*=(sequence& r) { /* ... */ }
define it as a free binary function outside the class body.
auto& operator*=(sequence& l, sequence& r) { /* ... */ }
Also, your function parameters need types. const& left does not have a type - you probably want const sequence& left.
I am not quite sure where my error is, also I am very new to programming and I know I am breaking a lot of standardization rules. I am learning. The user inputs two integers and it compares them, it always reports that the first integer entered is greater, even when it shouldn't. I want to say it is something wrong with my getlength method, but at this point I am not too sure.
#include "stdafx.h"
#include <iostream>
using namespace std;
template <class T>
//Function to find larger value a = first number, b = second number
T findLargerValue(T a, T b) {
return (a>b ? a:b);
}
//Class trip
template <class T>
class Trip {
public:
Trip<T>::Trip();
Trip(T a){
length = a;
}
T operator>(Trip yourTrip);
T getLength() {
return length;
}
private:
T length;
};
// Template function to carry into
/** This is where I seem to be losing my logic, I am trying to push larger of the two objects to the screen but it is only displaying the first user input This is supposed to take in the two bojects created and measure the lengths.**/
template<class T>
T Trip<T>::operator>(Trip yourTrip) {
if (length > yourTrip.getLength()) {
return length;
}
else{
return yourTrip.getLength();
}
}
template<class T>
Trip<T>::Trip()
{
}
int main()
{
// input for integer values
int num1 , num2 ;
cout << "Enter integer value 1: ";
cin >> num1;
cout << endl << endl;
cout << "Enter integer value 2: ";
cin >> num2;
//display message of first two numbers
cout <<"Frist Number was: " << num1 << " Second Number was: " << num2 << "\nThe Larger number of the two is "
<< findLargerValue(num1, num2) << endl << endl;
//input for double values
double num3, num4;
cout << "Enter double value 1: ";
cin >> num3;
cout << endl << endl;
cout << "Enter double value 2: ";
cin >> num4;
//display mesasge of second two numbers
cout << "Frist Number was: " << num3 << " Second Number was: " << num4 << "\nThe Larger number of the two is "
<< findLargerValue(num3, num4) << endl << endl;
// Display message for Trip function/objects
int fTlength, sTlength;
cout << "How many miles was your first trip: ";
cin >> fTlength;
Trip<int> fTrip(fTlength);
cout << endl;
cout << "How many miles was your second trip: ";
cin >> sTlength;
Trip<int> sTrip(sTlength);
Trip<int> tripLonger;
tripLonger = findLargerValue(fTrip, sTrip);
cout << "First trip in miles: " << fTlength << endl << "Second Trip in miles: " << sTlength << endl;
cout << "The longest trip was " << tripLonger.getLength() << " miles." << endl;
system("pause");
return 0;
}
You overloaded the operator > incorrectly. It should return true of false, but it returns (in this case) an integral value. It should look like this:
template<class T>
bool Trip<T>::operator>(const Trip& yourTrip)
{
return length > yourTrip.length;
}
Comparison operators should indicate whether or not the comparison is true. In your case, it was returning either length or yourTrip.length. This is a problem when findLargerValue calls operator > for the two objects. It checks if the result was true, and because any integer that isn't 0 is true, it was almost always returning the first object. If you had entered a negative number and a 0, it would have returned the second object.
I hope this question takes a simple fix, and I am just missing something very small.
I am in my second semester of C++ in college, and we are just getting into OOP. This is my first OOP program, and it is causing me a little problem. Here are the errors I am getting:
Member function must be called or its address taken in function displayGrid(int,Cell ( *)[20])
Member function must be called or its address taken in function Turn(int,int,Cell ( *)[20])
Member function must be called or its address taken in function Turn(int,int,Cell ( *)[20])
Warning: Parameter 'grid' is never used in function displayGrid(int,Cell ( *)[20])
Here is all of my code. I am aware It is much more code than necessary, sorry if it makes it more difficult. I was worried that I might accidentally delete something.
const int MAX=20;
//Struct Cell holds player and their symbol.
class Cell
{
private:
int Player;
char Symbol;
public:
Cell(void);
void setPlayer(int);
void setSymbol(char);
int getPlayer(void);
char getSymbol(void);
};
Cell::Cell(void)
{
Symbol ='-';
}
void Cell::setPlayer(int player_num)
{
Player = player_num;
}
void Cell::setSymbol(char rps)
{
Symbol = rps;
}
int Cell::getPlayer(void)
{
return Player;
}
char Cell::getSymbol(void)
{
return Symbol;
}
void Turn(int, int, Cell[MAX][MAX]);
void displayGrid(int, Cell[MAX][MAX]);
void main(void)
{
int size;
cout << "How big would you like the grid to be: ";
cin >> size;
//Checks to see valid grid size
while(size>MAX || size<3)
{
cout << "Grid size must between 20 and 3." << endl;
cout << "Please re-enter the grid size: ";
cin >> size;
}
int cnt=1;
int full;
Cell grid[MAX][MAX];
//I use full to detect when the game is over by squaring size.
full = size*size;
cout << "Starting a new game." << endl;
//Exits loop when cnt reaches full.
while(cnt<full+1)
{
displayGrid(size, grid); //calls function to display grid
if(cnt%2==0) //if cnt is even then it's 2nd players turn
cout << "Player 2's turn." << endl;
else
cout << "Player 1's turn" << endl;
Turn(size, cnt, grid); //calls Turn do each players turn
cnt++;
}
cout << endl;
cout << "Board is full... Game Over" << endl;
}
void displayGrid(int size, Cell grid[MAX][MAX])
{
cout << endl;
cout << " ";
for(int x=1; x<size+1; x++) // prints first row
cout << setw(3) << x; // of numbers.
cout << endl;
//Nested-For prints the grid.
for(int i=1; i<size+1; i++)
{
cout << setw(2) << i;
for(int c=1; c<size+1; c++)
{
cout << setw(3) << grid[i][c].getSymbol;
}
cout << endl;
}
cout << endl;
}
void Turn(int size, int cnt, Cell grid[MAX][MAX])
{
char temp;
char choice;
int row=0;
int column=0;
cout << "Enter the Row: ";
cin >> row;
cout << "Enter the Column: ";
cin >> column;
//puts what is in the current cell in "temp"
temp = grid[row][column].getSymbol;
//Checks to see if temp is occupied or not
while(temp!='-')
{
cout << "Cell space is Occupied..." << endl;
cout << "Enter the Row: ";
cin >> row;
cout << "Enter the Column: ";
cin >> column;
temp = grid[row][column].getSymbol; //exits loop when finally correct
}
if(cnt%2==0) //if cnt is even then its player 2's turn
{
cout << "Enter your Symbol R, P, or S (Capitals): ";
cin >> choice;
grid[row][column].setPlayer(1);
in >> choice;
}
//officially sets choice to grid cell
grid[row][column].setSymbol(choice);
}
else //if cnt is odd then its player 1's turn
{
cout << "Enter your Symbol r, p, or s (Lower-Case): ";
cin >> choice;
grid[row][column].setPlayer(2);
//checks for valid input by user1
while(choice!= 'r' && choice!='p' && choice!='s')
{
cout << "Invalid Symbol... Please Re-Enter: ";
cin >> choice;
}
//officially sets choice to grid cell.
grid[row][column].setSymbol(choice);
}
cout << endl;
}
Thanks alot for your help!
The following line:
cout << setw(3) << grid[i][c].getSymbol;
Doesn't call the function. Write this instead:
cout << setw(3) << grid[i][c].getSymbol();
Likewise for the other error messages.
The warning is generated because the erroneous line is the only time displayGrid uses the grid parameter.
You forgot the function parens:
cout << setw(3) << grid[i][c].getSymbol;
should be:
cout << setw(3) << grid[i][c].getSymbol();