C++ While Loop to work - c++

Since I know the basics of Python (3), I decided to take the programs I did in Python and type them in C++ to get the hang of C++.
Problem: When you type "TheEnd" for the name, I wish the program to end, but for some reason if you type "TheEnd" it will ask for the other fields once, and then end. Is there a way for the user to type "TheEnd" when asked for a name and the program just ends? (I tried putting the while loop in different areas, but to no avail.)
Here is what I have:
#include <iostream>
#include <string>
//While loop.
using namespace std;
main()
{
string name;
string major;
float hours, qualityPoints, GPA;
while (name!="TheEnd") //Here's the while loop
{
cout<<"Please enter your name. "<<endl;
cin>>name;
cout<<"Please enter your major. "<<endl;
cin>>major;
cout<<"List the hours you've completed so far. "<<endl;
cin>>hours;
cout<<"List how many quality points you have. "<<endl;
cin>>qualityPoints;
GPA = qualityPoints / hours;
if (GPA >= 3.4 and hours >= 12)
{
cout<<name<<endl;
cout<<major<<endl;
cout<<"You made the Dean's List."<<endl;
}
else
{
cout<<"You did not make the Dean's List."<<endl;
}
}
}

It is asking because your condition is tested at the beginning and then after asking all fields.
The smallest change of your code would be following changes:
for(;;) // Former while(name!="TheEnd")
{
cout<<"Please enter your name. "<<endl;
cin>>name;
if(name=="TheEnd")
break;
Some explanation:
Usually it is common practice to use for(;;) instead of while(true) as endless loop. The reason for that lies in the fact the some compiler emit(ted) warnings for constant expressions in if/while (for e.g. VS 2005 which was AFAIK widely used). In most professional projects warnings are taken as error.
Every loop (for/while) can be exit by using break. So you have no loop condition but a exit condition. I decided to wrote this solution because it needed the smallest change to your sample code. Also there is no (easy) way to keep your breaking condition as part of the while condition.
Keep the while(name!="TheEnd") and only add the if after the cin is not good pratice. You produce "cargo cult programming" code with that.

Related

I'm unsure exactly why the 'counter' variable isn't responding in the way I would like it to

Please bear with me since I am very new to C++ and coding in general.To the point where this is my second or third time using arrays. Here is the code in question:
#include <iostream>
using namespace std;
int main()
{
int day,month,counter;
int year[12]={31,28,31,30,31,30,31,31,30,31,30,31};
cout<<"Input a day of a month";
cin>>day;
cout<<"Input the month of the year";
cin>>month;
for(int x=0;x>12;x++)
{
cin>>year[x];
counter+=year[x];
}
cout<<"The Date is " <<day<<" / "<<month<<" and, "<<endl;
cout<<"The number of days until this date is reached again is:"<<counter<<endl;
}
I am trying to have the code show an imputed date by the user and the number of days until that date is reached again. However the counter variable is only showing 0. I am decently sure this is some form of logic error I have yet to find.
Your loop
for(int x=0;x>12;x++)
sets x to 0 and then checks if it's greater than 12, which it isn't, and thus ends doing nothing.

I am trying to make a finals grade calculator, but it isn't working

C++ beginner here.
So, I'm trying to make this code function like a finals grade calculator, but it isn't working. It gives back the value of 100 every time. What's wrong?
#include <iostream>
using namespace std;
int main()
{
double grade, des, worth, per, grade1, tgrade, fgrade;
cout<<"What is your current grade in the class?"<<endl;
cin>>grade;
cout<<"What is your desired grade in the class?"<<endl;
cin>>des;
cout<<"How much is your final exam worth? (Percent of total grade)"<<endl;
cin>>worth;
per=1-(worth/100);
grade1=grade*per;
fgrade=100;
while ((tgrade-0.01)<=des<=(tgrade+0.01)) {
fgrade=fgrade-1;
tgrade=grade1+(fgrade*(worth/100));
}
cout<<"You need a grade of "<<fgrade<<"% on your final exam to reach your desired grade in your class. Good Luck!"<<endl;
return 0;
}
I can see the logic you're trying to achieve in the loop condition, however <= is a binary operator, so you need to have two conditions which you combine with &&.
while((tgrade-0.01) <= des && des <= (tgrade+0.01))

cout doesn't works properly on my program, can somebody help me?

enter image description hereI am using the STL in c++ and inside a bucle the cout doesn't prints correctly a float.
my program ads values to a vector and then passes it to a function to see if the condition exist, actually it works perfectly but just the cout doesn't word, I already tried using printf() but it gave the same result.
note:please algo give me feedback on my question is the first time i do one and English is not my natal language
my code:
#include<bits/stdc++.h>
#include<vector>
using namespace std;
void isthereanumber(vector<float> array);
int main(){
string ans;vector<float> array;float number;
do{
fflush(stdin);
cout<<"insert a value for the vector: "<<endl;
cin>>number;
array.push_back(number);
fflush(stdin);
cout<<"would you like to keep adding values to the vector? "<<endl;
getline(cin,ans);
}while(ans.compare("yes")==0);
isthereanumber(array);
return 0;
}
void isthereanumber(vector<float> array){
float suma =0;
for(vector<float>::iterator i=array.begin();i!=array.end();i++){
for(vector<float>::iterator j=array.begin();j!=array.end();j++){
if(i!=j){
suma = suma+array[*j];
}
}
if(suma=array[*i]){
cout<<"there is a number that the addition of every number in the array except the number is equal to the number \n";fflush(stdin);
cout<<"the number is: "<<suma;/*here is the cout that doesnt works properly or perhabs is something else i don't know*/
return;
}
}
cout<<"there is not a number with such a condition: ";
return;
}
As stated by cleggus already there are some issues present. Those need to be adressed first. After that there's a logical error in that suma just keeps growing.
Given the input 5,5,10 once we test for 10 we would like suma to be set to 0 again for it to work but it will be something like 30 now instead.
That can be solved by moving suma inside the outer loop.
Working example for input 5,5,10: https://godbolt.org/z/gHT6jg
I think you may have a couple of issues...
In your for loops you are creating iterators to the vector, but rather than just dereferencing them to access the indexed element you are dereferencing them and then using that as an index to the same vector.
Also Your last if statement has an assignment = rather than a comparison ==.
I believe this is closer to what you are trying to achieve (sorry I haven't had time to compile and check):
for(vector<float>::iterator i=array.begin();i!=array.end();i++){
for(vector<float>::iterator j=array.begin();j!=array.end();j++){
if(i!=j){
suma = suma+*j;
}
}
if(suma==*i){
cout<<"there is a number that the addition of every number in the array except the number is equal to the number \n";fflush(stdin);
cout<<"the number is: "<<suma;/*here is the cout that doesnt works properly or perhabs is something else i don't know*/
return;
}
}

C++ - Using specific character input for 'if' statements

I am, for lack of a better word, an absolute programming novice. And as it stands, I've been flung head first into programming something in two or three languages.
As part of an assignment, we have been tasked with essentially recreating a heads/tails flip, in the form of a random chance game.
The way it works is the player has ten credits to start off with. They are asked to input a wager, and then they are asked heads or tails. Picking either heads or tails sets off a number generator, and depending on the value, they may well end up winning or losing their wager.
I coded a similar version of this using HTML/CSS/JS, and it works. I'll leave a puush link to the file so you can view it yourselves to get an idea of what I'm trying to do: http://puu.sh/bP2V7/2ef63f4a1c.html
I'm trying to do, functionally, the same thing in C++ in the form of a command application. I know the code I'm using works fine, and it compiles without much of a hitch. It's a bit annoying that it closes down rather than resetting to a previous line, but that's a hurdle I'll jump over when I get to it.
I had a look around, and to be honest, whilst a few of the things may well work, I'm admittedly relatively clueless and some of the programmer speak kinda flies over my head.
It's probably because I'm being thrown into it and I'm not used to it yet, but as it stands, I need your help.
My code simply works as follows (simplified to save time):
int main()
{
int points, wager;
points = 10;
output "HEADS OR TAILS?";
if (player has 1 point or more)
{
output "Input wager";
input wager value;
output "Wager is (player input)";
output "Heads or Tails?";
input h or t; //This was what I wanted
if (player selects 'heads') //For sake of simplicity, the code
{ //here will account for both heads
int heads; //and tails.
srand(NULL);
heads = random number 1 and 2;
if (heads = 1)
{
output "HEADS!";
output "You win 'wager'!";
points = points + wager;
}
if (heads = 2)
{
output "TAILS!";
output "You lose 'wager'!";
points = points - wager;
}
}
}
if (player has 0 points)
{
output "GAME OVER";
}
}
What I want to do is have the user input either an 'h' or a 't' to determine whether or not they want heads or tails.
In your programming class, they will have told you what they expect you to use as tools for input and output, eg char inputChar; cin >> inputChar; or similar. Use whatever they told you to use in the style they want you to use, eg
cout << HEADS_OR_TAILS_PROMPT;
char inputChar;
cin >> inputChar;
switch(inputChar) {
case 'h':
{
... // code for the heads case
break;
}
case 't':
{
... // code for the tails case
break;
}
default:
// whatever you want to do if they didn't input a valid option
}
Although, to be honest, asking your professor is going to get you a better answer for what the grader is expecting than asking us is.

I am getting breaking point error in this c++ program of mine,have a look. compiler visual c++ 2010 [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
error snapshot : https://rapidshare.com/files/3201989698/Capture5.JPG
code :
#include<fstream>
#include<conio.h>
#include<Windows.h>
#include<iostream>
using namespace std;
int ch_m;
HANDLE hConsole;
class budget
{
public :
float balance;
string due_name,loan_name;
int year,month;
float due_pay,loan_given;//due_pay due to be paid
budget()
{
balance=0;
month=1;
due_name="NO BODY";
loan_name="SAFE";
year=0;
balance = 0;
due_pay=0;
loan_given=0;
}
char get_data();
void show_data();
void budget_menu();
void balance_menu();
int yr()
{
return(year);
}
int mont()
{
return month;
}
};
void gotoxy(int x,int y)
{
HANDLE hConsoleOutput;
COORD dwCursorPosition;
cout.flush();
dwCursorPosition.X=x;
dwCursorPosition.Y=y;
hConsoleOutput=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition
(hConsoleOutput,dwCursorPosition);
}
char budget :: get_data()
{
char ch_b;
gotoxy(5,2);
cout<<"Enter Month :";
cin>>month;
gotoxy(5,4);
cout<<"Enter year :";
cin>>year;
gotoxy(5,6);
cout<<"Enter your balance for the current month and year in Rs :";
cin>>balance;
do
{
gotoxy(6,9);
cout<<"Continue adding records?(y/n)\n";
cin>>ch_b;
}while(tolower(ch_b)!='n'&&tolower(ch_b)!='y');
return ch_b;
}
void budget :: show_data()
{
gotoxy(5,2);
cout<<"Month :"<<month;
gotoxy(5,4);
cout<<"Year :"<<year;
gotoxy(5,6);
cout<<"Your balance for the current month and year in RS :"<<balance;
_getch();
}
void budget:: budget_menu()
{
system("cls");
gotoxy(12,5);
cout<<"---------------------------------------";
gotoxy(12,6);
cout<<"Budget Menu";
gotoxy(12,7);
cout<<"---------------------------------------";
gotoxy(12,10);
cout<<"1) Balance";
gotoxy(12,12);
cout<<"2) Loan Given";
gotoxy(12,14);
cout<<"3) Due to be paid";
gotoxy(12,16);
cout<<"4) Exit";
gotoxy(14,17);
cout<<"Enter your choice\n";
cin>>ch_m;
switch(ch_m)
{
case 1:
balance_menu();
break;
default:
system("cls");
gotoxy(15,8);
cout<<"Wrong Input!!";
}
}
void write_balance()
{
system("cls");
budget b;
ofstream f1;
f1.open("balance.dat",ios::app|ios::binary);
char ch;
do{
ch = b.get_data();
f1.write((char*)&b,sizeof(b));
}while(tolower(ch)=='y');
f1.close();
}
void read_balance() //PROBLEM AFTER ENTERING THIS FUNCTION
{
system("cls");
budget b;
ifstream f1;
f1.open("balance.dat",ios::in|ios::binary);
while(f1.read((char*)&b,sizeof(b)))
{ b.show_data();
}
system("cls");
cout<<"No More Records To Display!!";
getch();
f1.close();
}
void budget :: balance_menu()
{
int ch_bm;//balance menu choice
char coni;//continue?
system("cls");
gotoxy(12,6);
cout<<"1) Add current month and year balance";
gotoxy(12,7);
cout<<"2) Modify a balance";
gotoxy(12,8);
cout<<"3) Search a balance";
gotoxy(12,9);
cout<<"4)Delete a Record";
gotoxy(12,10);
cout<<"5) Display all records";
gotoxy(12,11);
cout<<"6) Back to previous menu";
gotoxy(12,12);
cout<<"7) Exit";
gotoxy(14,15);
cout<<"Enter your choice\n";
cin>>ch_bm;
switch(ch_bm)
{
case 1 :write_balance();
break;
case 5:
read_balance();
break;
default :
system("cls");
gotoxy(15,8);
cout<<"Wrong Input!!";
}
if(ch_bm!=6)
{
system("cls");
gotoxy(15,8);
cout<<"Continue?";
cin>>coni;
if(tolower(coni)=='y')
{
balance_menu();
}
}
getch();
}
void main()
{
system("cls");
budget b;
b.budget_menu();
_getch();
}
first go to option 1/1 to create the file and then 1/5 to read the contents where you will get breaking point error....
till now i have included only read and write option .
It has been 3 weeks.. i m stuck here
i have tried a lot of things
My code is working fine in turbo c++ but not in vc++
this code is to keep data of one's budget. function having problem is highlighted using comment.
Here's my review:
Use double not float unless smaller variable size is needed.
Assign 0.0 to floating point quantities. Append with 'F' if for
floating point.
Prefer one variable definition per line. Makes for easier development and
maintenance. The cost in build time is very negligible.
Prefer to use initialization list in constructors, such as :
balance(0.0), //...
Be consistent in your return statements. Parenthesis are not
required.
Do you need to have cursor positioning? It is a difficult issue
in Windows.
The C++ default I/O streams may not be compatibile with Windows
console positioning.
You are not storing records. The last iteration will always
overwrite the previous record.
Why do you need to return the operator's response from get_data?
Definitely get rid of the cursor positioning. It is getting in the
way of your development. Add it back in, if necessary, after your
program is working correctly and is robust.
You don't give the operator a chance to correct the selection and
try again. Not good
Prefer not to use binary I/O, especially when writing structures
and classes to files. If the class or structure layout changes or
the compiler inserts padding between fields your reading may not be
assigned correctly. Also, verify your data in the file is going to
be more difficult. I suggest using one text line per record and
each field separated by a tab, comma or other delimiter. This
allows you to import your data into other applications, such a
spreadsheet, for verification. Text is a lot easier to verify than
binary data.
Prefer to have I/O methods in your class / object. That way you
can make one easy statement like file << my_budget;
If you didn't use x,y positioning, you could declare the menu as
one constant text literal and output it (much easier and faster)
than having to display one line at a time. Easier to modify and
maintain too.
The main function returns int, always. Use return
EXIT_SUCCESS; if necessary.
In your methods, the budget variables are local and will
disappear upon return from the method. Reference the class
variable instead.
Always check for I/O errors. This could be where your issue is.
Pause the console before clearing it. Try this:
cin.ignore(100000, "\n");