#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main()
{
string name;
double gpa;
double high = 0;
stack<string>names;
for (int i=0;i<7;i++)
{
cout << " Enter student's name and gpa " <<endl;
cin >> gpa ;
cin >> name ;
if (gpa > high)
{
names.destroyStack();
high = gpa;
names.push(name);
}
else
if (gpa==high)
{
names.push(name);
}
}
cout << "Highest gpa is " << high << "Names with the highest gpa are"<< endl;
while (!names.empty)
{
cout << names.top() << endl;
names.pop();
}
return 0;
}
In order to display only the names with the highest gpa, I have to put a code to remove the stack before with the lower gpa scores.So for this I thought I could use the "destroystack()" operation but when I use that and try and execute it, the compiler says that the destroyStack wasn't declared in the scope.
This AND the bottom one where I want to display the stack.It even says that empty wasn't declared.
I'm confused with these errors and I don't know what it means by declaring the operations? I'm using codeblocks (Not Visual studio) so does that affect anything?
Because, quite simply, there is no such function destroyStack in std::stack. I have no idea where you got the idea that there is.
This code should work to empty your stack:
replace:
names.destroyStack();
with:
while (!names.empty())
{
names.pop();
}
As you can see, empty is a function; it returns a value. In this case, it returns a boolean (true/false), so you'll need to have parenthesis after it, in order to call it.
That's why you're getting the message about empty not being declared; it means that the compiler is looking for a variable called empty, but it doesn't exist. By adding the parens, you're telling it that you want to call a function, not access a variable.
The "while loop" iterates through all of the items in the stack until the stack is empty. This effectively means that, for every item that the stack has in it, the item is "pop'd" off (pop is also a function, but it returns the item that was on the stack). Eventually, the stack has nothing left in it, and the while loop exits, because empty() returns true.
For a good reference on what functions and properties the stack template has on it, check out:
http://www.cppreference.com/wiki/container/stack/start
You should implement that destroyStack yourself. A function such as:
void destroyStack(stack<string>& _stack)
{
// Do whatever
}
And call it with:
destroyStack(names);
empty should be empty() instead.
Your editor, codeblocks or Visual Studio, doesn't affect anything.
Related
So I'm having some trouble with my program. It doesn't seem to fill the array properly. It dosen't seem to populate pass element 0, even though I'm increasing i. When I debug and go back, i remains zero. Should I be doing something different? I feel like I'm passing or updating the array improperly. Can't really use any STL libraries. Thank you in advance for any help.
struct Client
{
string name;
string zip;
double balance;
};
Client bAccounts [30]; //structural array in main()
int addClnt(Client(&bAccounts)[30], int); //prototype
int addClnt(Client(&bAccounts)[30], int clientCount) //function to add
elements
{
cout << "Enter Account Name:" << endl;
cin >> bAccounts[i].name;
cout << "Enter Account Zip:" << endl;
cin >> bAccounts[i].zip;
cout << "Enter Account Balance:" << endl;
cin >> bAccounts[i].balance;
cout << "Enter Last Transaction" << endl;
cin >> bAccounts[i].lastTrans;
clientCount++; //to return number of clients added
i++; //to populate different element of array on next call of function.
return clientCount + 1;
}
So I added + 1 to return clientCount and then set i = clientCount. However, clientCount remains at zero and dosen't update.
The reason the array doesn't have any values after the first one is because you never reach passed the first element. You increment i at the end of the function, but at the top of your addClnt function, i is set back to 0 . This will just keep resulting on overwriting the old previous data
EDIT:
#include <iostream>
//use pass by reference (&)
void add_client(int& index_loc){
//do whatever
//this changes the actual value passed into the function
index_loc++;
}
int main(){
int loc = 0;
add_client(loc);
add_client(loc);
add_client(loc);
//outputs 3
std::cout << "current #: " << loc << "\n";
}
clientCount is only getting incremented in that functions scope. When that function goes to it's return statement, all variables and all the work it did has completely died.
You are passing clientCount by value and not by reference, so clientCount will always be 0, and incrementing it inside that local function won't actually change clientCount's value outside of the function.
What you need to do is pass it by reference.
EDIT: The chosen answer does not explain why his solution works. The answer provided is incorrect.
The reason why the code works because again, you pass by reference and not by value.
i am trying to make a program to check and list the genders of a number of student, m being fem and l being male.
I'm not sure what's wrong with my code but when i print out the m and l variable they have either really huge.
Have been trying to solve this for hours, your help is greatly appreciated, cheers.
P.S sorry for my bad english.
#include<iostream>
#include<string>
using namespace std;
main()
{
char gender[20];
int jlh,i,j,m,l;
cin>>jlh;
system("cls");
for(i=0;i<jlh;i++)
{ cout<<"Data "<<i+1<<endl;
cout<<"Enter your gender - "<<endl;
cin>>gender[i];
}
m,l=0;
for(i=0;i<jlh;i++){
if(gender[i]=='p'){
m=m+1;
}
else if(gender[i]=='l'){
l=l+1;
}
}
cout<<endl<<l<<endl;
cout<<m;
}
The line
m,l=0;
does not work as you expect. Look up the comma operator, it evaluates the first operand (just m in this case), discards the result, and evaluates and returns the second operand. So only l is set to zero. I would recommend moving the declaration to this line and initializing the variables in one go, like so
int m=0, l=0;
for (int i=0; i<jlh; i++)
...
I would also move the declaration of variables like i to where they are needed, as shown above; there is no need to put all declaration at the beginning of the function.
Then the output
cout<<endl<<l<<endl;
cout<<m;
places the endl before and after the first variable, but not after the second. You should have an endl after the last line of your output, otherwise your console prompt is right after your value. It would improve readability to have something like this:
std::cout << "Number of females: " << m << std::endl;
std::cout << "Number of males: " << l << std::endl;
You should also make sure that not more than 20 values are entered, as your array has this size. But there is not even a need for this (maybe there is in your real code, but not in the MCVE): You can just increment the variables when reading the input, no need to store it in the array. This gets rid off this arbitrary limit. If you really need the values, you should use a std::vector instead of a fixed size array.
Im doing an excercise sheet to get an understanding of functions and I am currently working on the following question.
Write function prototypes for each of the following:
A function HasValue that may be passed a reference to an array, the size of the array and a
search value. The function should return true if the search value exists in the array
In my code I have sent the contents of the array, the array size and the value to be searched in the array to the bool function.
In the function I compared the value to each element of the array using a for loop.
I then created a variable count in the function that will be incremented if the value matches any element in the array.
I then used an if else statment to return true if count is greater than 0 and false if count is equal to 0. The problem is however that the function is only returning true thus the output will always be "this number appears in the array"
Logically these steps seem correct to me but obviously there is a flaw somewhere that I cant see. I presume its just I do not have a decent understanding of Bool functions yet but if someone could explain where and why I'm going wrong it would be greatly appreciated in my learning process to understanding functions and c++.
#include <iostream>
#include <iomanip>
#include "stdafx.h"
using namespace std;
bool HasValue(int Array[], int size, int Value);
int main()
{
int value;
int Array[10]{ 3,5,6,8,9,1,2,14,12,43 };
cout << "enter value you wish to search for in array " << endl;
cin >> value;
HasValue(Array, 10 , value);
if (true)
cout << "This number appears in the array " << endl;
else
cout << "This number does not appear in the array " << endl;
return 0;
}
bool HasValue(int Array[], int size, int Value)
{
int count = 0;
for (int i = 0; i < size; i++)
{
if (Value == Array[i])
{
count++;
}
}
if (count > 0)
{
return true;
}
else
return false;
}
You test code is the problem
HasValue(Array, 10 , value);
if (true)
cout << "This number appears in the array " << endl;
else
cout << "This number does not appear in the array " << endl;
This ignores the return value of HasValue and always prints "This number appears in the array".
HasValue(Array, 10 , value);
This line of code executes the function but ignores the returned value. When a function returns a value, you need to assign it to a variable:
bool result = HasValue(Array, 10 , value);
Then if (true) does not have any reference to the returned value. The true inside the if will cause the first cout to always print. You will never see the output from the else. But once you have the return value in a variable, you can use it in the if:
if(result)
You can reduce this all to one line of code, if you want:
if(HasValue(Array, 10 , value))
Now the if statement will directly test the return value from HasValue(). In this particular case, combining the code into a single line seems reasonable. You must be careful doing this, though. When you combine too much into a single line, the code becomes more difficult to debug. You will need to find a balance between readability and convenience as you continue learning how to program.
I am making a program that the user inputs integers and outputs them in reverse. It is a recursive function. The Problem now is that it outputs an infinite of 0's. Please tell me where is the error in my code. and I need some pointers. Please help.
#include <iostream>
using namespace std;
void printreverse(int);
int main()
{
int x;
cout << "Enter numbers: ";
cin >> x;
printreverse(x);
return 0;
}
void printreverse(int x)
{
if(x<10)
cout << x;
else
cout << x%10;
printreverse(x/10);
}
You have wrong identing in printreverse. It should be like this:
void printreverse(int x)
{
if(x<10)
cout << x;
else
cout << x%10;
printreverse(x/10);
}
First it prints x or x%10, then it recurses regardless of what x is. If you wanted more than one statement done in a consequent or alternative you need to use a block. Blocks are denoted with {} in C-decendants. They are so usual that some people actually think conditionals and control flow syntax need to have them. Anyway if the identing was the intended behaviour you should write it like:
void printreverse(int x)
{
if(x<10) {
cout << x;
} else {
cout << x%10;
printreverse(x/10);
}
}
Whenever I use braces on one term in an if I add them for every one even when it's not really needed. Some coding standards, like PSR2, require blocks always to remove the chance of ever getting bugs like this.
C++ is not Python. You need to surround your else block by braces, like so
else
{ // need brace here
cout << x%10;
printreverse(x/10);
} // and here
otherwise only the first statement after the else is being executed (and the final printreverse(x/10) will always be executed, even for 0, so you end up overflowing the stack).
I recommend you to always put braces, even for a single statement in an if/else, precisely for reasons similar to the one you just bumped into.
I use Visual C++ 2010 Express Edition to compile and run the .exe files I write in the C++ programming language. I am trying to create a loop-based logic using C++ to ask the user how many entries he chooses to enter, and ask questions limited to that no. of entries. For example I want to output, "How many characters do you wish to enter?: " Say the user gives the answer as '3' which is stored in the int variable 'entries'. I then want to keep asking the question 3 times before it stops and continues with the next line of code. I hope you understand, here is a block of code to demonstrate what I am doing:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "How many values do you need to enter?: ";
int entries;
cin >> entries;
int offset, number;
string valueName[50];
float valueValue[50];
for (offset = 0; offset < entries; offset++)
{
cout << "Enter " << number << " Value Name: ";
cin >> valueName[offset];
cout << "Enter " << valueName[offset] << "\'s value: ";
cin >> valueValue[offset];
for (number = 1; number <= entries; number++)
{
}
}
char response;
cin >> response;
return 0;
}
Strangely when I run this simple program, it fails when I enter the value's name to be inserted into the 0th element of the valueName[] array. It just pauses the execution of the program and a dialog box pops up saying "Runtime Check Failure #3 - Variable 'number' is being used without being initialized!" Another problem regarding this program is that, for quite some time, when I ran this program this "Runtime Check Failure #3" box never appeared, and when it didn't, the number value went wrong, and first started with 1, and then for the next loop jumped to 6, and then repeated 6 again for the next loop! Please help me! I've checked online scouring this problem everywhere, but it just doesn't apply to my type of problem! Is it because the variables are out of scope? But they're declared outside the for loops right? So please help me!
The runtime is telling you the truth, the following line comes after you have declared number as an int but have not given it a value.
cout << "Enter " << number << " Value Name: ";
In your code you declare the following, in C++ this means give me 2 ints but the values are not defined yet, e.g.
int offset, number;
Change it to something like this ..
int offset = 0;
int number = 0;
You are printing the variable number without assigning to it first, i.e. it's uninitialized. When it prints some random number it's because that what happens to be in the memory at the time you run the program. Assign a value to it before you use it.
The problem is exactly the error message you're getting. You're using the variable number without initializing it.
You use the variable right here, at the top of your loop, when it hasn't been initialized to anything yet:
cout << "Enter " << number << " Value Name: ";
What is your intention with the number variable? It doesn't really seem to be serving any purpose. If you want to print which entry you're currently on, you could use the offset variable instead, like this:
cout << "Enter " << offset << " Value Name: ";
But that still seems a little unclear to me.
But the reason that you're having a problem is because the value is uninitialized, so you're experiencing undefined behavior. This is also the reason that Visual Studio doesn't always catch it; it will probably always catch in Debug mode, but in Release mode it will almost never catch it. You need to initialize all your variables before you use them.
In my case it was because an extern variable was declared twice.