Why won't the string cout - visual-c++

O.F community! I'm very new to c++ and I decided to create my own game.
My issue is that at one point in the game the player is asked to answer 3 things:
-Gender
-Age
-Setting
void assessment()
{
cout << "Now that the characteristics have been selected. Let's review what they are:\n\n";
cout << "Press any key to continue\n\n";
cin >> anykey;
cout << "You are a " << ageNumber << " year old " << gender; //incomplete - needs //<< setting;
}
The issue is with gender not being displayed. It can cout << ageNumber fine. But when the game is played and this part is reached this is what it says:
Now that the characteristics have been selected. Let's review what they are:
Press any key to continue
1
You are a 16(that is what I put for ageNumber earlier on) year old . <- Notice how "old" and "." have a space? As if the string gender is read as a blank.
EDIT: It is supposed to say:
You are a 16 year old male/female/it.
This is the part that determines the gender.
void fate()
{
cout << "Before we begin, a few characteristics must be selected\n\n";
cout << "Gender?\n\n";
cout << "1. Male\n";
cout << "2. Female\n";
cout << "3. Other\n\n";
cin >> genderNumber;
cout << "Now your next characteristic...Press any key to continue\n\n";
cin >> anykey;
cout << "What is your age? (Must be younger than 50 to play)\n\n";
cin >> ageNumber;
setting2();
if (genderNumber == 1)
{
string gender = "male";
}
else if (genderNumber == 2)
{
string gender = "female";
}
else if (genderNumber == 3)
{
string gender = "'it'";
}
else
{
"invalid input\n\n\n\n\n\n";
fate();
}
===========================================================================================
This is the full code:
#include <iostream>
#include <string>
using namespace std;
void rules();
void controls();
void start();
void fate();
void assessment();
void setting2();
int fateNumber;
int anykey;
int ageNumber;
int settingNumber;
int genderNumber;
string gender;
string setting;
int main(int argc, char** argv)
{
cout << "===W E L C O M E T O C H O O S E Y O U R F A T E=== \n\n";
cout << "Press any key to continue\n";
cin >> anykey;
start();
}
void controls()
{
cout << "Throughout this game will you be making choices, each choice will have a corresponding number next to it. Press the letter to the corresponding choice you want to make. Press any key to continue\n";
cin >> anykey;
cout << "Here is an example...you are a cat, you can either\n\n";
cout << "1. Meow\n\n";
cout << "2. Hiss\n";
cout << "Press any key to continue\n";
cin >> anykey;
cout << "If I wanted to Hiss I would press the 2 key\n\n";
cout << "Press any key to continue on to the rules\n\n";
cin >> anykey;
rules();
}
void rules()
{
cout << "#1 You will be given a set number of choices. Press any key to continue\n\n";
cin >> anykey;
cout << "#2: There are 2 factors to this game. Press any key to continue\n\n";
cin >> anykey;
cout << "#3: The first factor is that either you live or you die. Press any key to continue\n\n";
cin >> anykey;
cout << "#4: The second factor is that if you live, your character will be judged based on events you've made. You can still live, but you might have a good or bad effect on the people around you. Press any key to continue\n\n";
cin >> anykey;
cout << "Let's play shall we?";
}
void start()
{
cout << "You shall begin a journey that'll decide either you make it or you don't. Press any key to continue\n\n";
cin >> fateNumber;
cout << "But before we start...The game needs to be explained.\n\n\n\n";
cout << "Controls(1 key)---------------------------Rules(2 key)---------------Skip(3 key) \n\n";
cin >> fateNumber;
if (fateNumber == 1)
{
controls();
}
else if (fateNumber == 2)
{
rules();
}
else if (fateNumber == 3)
{
fate();
}
else
{
cout << "invalid key\n\n\n\n\n\n\n";
start();
}
}
void fate()
{
cout << "Before we begin, a few characteristics must be selected\n\n";
cout << "Gender?\n\n";
cout << "1. Male\n";
cout << "2. Female\n";
cout << "3. Other\n\n";
cin >> genderNumber;
cout << "Now your next characteristic...Press any key to continue\n\n";
cin >> anykey;
cout << "What is your age? (Must be younger than 50 to play)\n\n";
cin >> ageNumber;
setting2();
if (genderNumber == 1)
{
string gender = "male";
}
else if (genderNumber == 2)
{
string gender = "female";
}
else if (genderNumber == 3)
{
string gender = "'it'";
}
else
{
"invalid input\n\n\n\n\n\n";
fate();
}
if (ageNumber >= 50 && ageNumber < 100)
{
cout << "Didn't you read the age rating dumbass? Younger than 50...\n\n";
}
else if (ageNumber < 50 && ageNumber > 22)
{
setting2();
}
else if (ageNumber <= 22 && ageNumber >= 16)
{
setting2();
}
else if (ageNumber < 16 && ageNumber >= 0)
{
setting2();
}
else if (ageNumber >= 100)
{
cout << "More than a century old and you expect me to believe you got this far? Bullshit.";
}
else
{
cout << "Error - Invalid number\n\n\n\n\n\n";
cout << "what is your age again?\n\n";
cin >> ageNumber;
}
}
void assessment()
{
cout << "Now that the characteristics have been selected. Let's review what they are:\n\n";
cout << "Press any key to continue\n\n";
cin >> anykey;
cout << "You are a " << ageNumber << " year old " << gender << ". You are " << setting << endl << endl;
if (settingNumber == 1)
{
string setting = "home";
}
else if (settingNumber == 2)
{
string setting = "jail";
}
}
void setting2()
{
cout << "Alright and lastly pick your setting\n\n";
cout << "1. Home sweet home\n";
cout << "2. Vacation \n";
cout << "3. Jail\n\n";
cin >> settingNumber;
assessment();
}
=======================================================================================
Any help is appreciated ^^ Code on!

Output (thru ofstream-s like cout) is buffered in C++. You want
cout << flush;
or
cout << endl;
to ask the buffer to be flushed (endl manipulator also emits a new line but flush does not).
So code:
cout << "You are a " << ageNumber << " year old " << gender << flush;
or
cout << "You are a " << ageNumber << " year old " << gender << endl;
Also, your gender should be declared at a wider scope:
if (genderNumber == 1) {
string gender = "male";
}
should become (to refer to the global gender)
if (genderNumber == 1) {
gender = "male";
}
BTW, if you enabled all warnings with your compiler (e.g. compile with g++ -g -Wall -Wextra, if using GCC, e.g. on Linux) you should have been warned. And of course, you should use the debugger (e.g. gdb, at least on Linux) and step into your code with it.

Related

How to insert a new line in a text file using C++

I have to write a program in C++ that asks user to enter lines and store them in a text file.
void create_file(char name[80])
{
char line[80],op;
ofstream fout(name);
do
{
cout << "Enter the line you want to enter in the file:" << endl << endl;
gets(line);
fout << line << endl;
cout << "\nDo you want to enter another line?" << endl;
cin >> op;
}
while(tolower(op) == 'y');
cout << "File created successfully!" << endl;
fout.close();
}
The problem is that the text is not being stored in different lines.
I have to use Turbo C++ for this program.
Minimal, Reproducible Example:
#include<iostream>
#include<fstream>
#include<conio.h>
#include<stdio.h>
#include<ctype.h>
using namespace std;
void show(char name[80])
{
char line[800];
cout << "Contents of the file:" << endl << endl;
ifstream fin (name);
while(!fin.eof())
{
fin.getline(line,80);
if(fin.eof())
break;
cout << line;
}
}
void create_file(char name[80])
{
char line[80],op;
ofstream fout(name);
do
{
cout << "Enter the line you want to enter in the file:" << endl << endl;
fflush(stdin);
gets(line);
fout << line << endl;
cout << "\nDo you want to enter another line?" << endl;
fflush(stdin);
cin >> op;
}
while(tolower(op) == 'y');
cout << "File created successfully!" << endl;
fout.close();
show(name);
}
int main()
{
char name1[80];
cout <<"Enter the name of the text file:" << endl;
gets(name1);
create_file(name1);
return 0;
}

Printing out a Dynamic Arrays filled with pointers pointing to classes not printing out correct print function?

So, I have a homework problem with these steps:
1. Prompt the user for the number of people to create, then create an array of personType pointers to hold them.
Loop through the array, prompting the user to decide whether to create a personType,r studentType, and professorType and enter the data as necessary, then use appropriate new constructor.
Finally, loop through the array again and call the (virtual) print method for each person.
Delete the objects, deallocate the array and quit.
In this program, there are already 3 classes: personType, studentType, and professorType. studentType and professorType are derived from personType. Each of them has their own void print() function, with studentType and professorType print() funtions overriding personType print(). Yet, when I try to print, I can only seem to call personType print() method.
I have tried rewriting my code to use the constructors to populate each pointer in the array of pointers. I have also tried making personType print() method function protected, and adding a virtual print() method (though I don't think I fully understand virtual functions yet).
#include "personType.h"
#include "studentType.h"
#include "professorType.h"
int main()
{
int num;
personType **people;
string fName;
string lName;
string address;
double height;
string DOB;
char gender;
string id;
double gpa;
string classification;
string employeeID;
string department;
string degree;
int choice;
cout << "Please enter the amount of people you wish to create: ";
cin >> num;
while (cin.fail()) {
cin.clear();
cin.ignore(256, '/n');
cout << "Please enter the amount of people you wish to create: ";
cin >> num;
}
people = new personType *[num];
system("pause");
system("cls");
for (int i = 0; i < num; i++) {
cout << "1 - Person, 2 - Student, and 3 - Professor" << endl;
cout << "Enter the type of person you wish to create: ";
cin >> choice;
while (cin.fail() && choice < 1 && choice > 3) {
cin.clear();
cin.ignore(256, '/n');
cout << "Enter the type of person you wish to create (1-3): ";
cin >> choice;
}
cout << "Person " << i + 1 << endl;
cout << "First Name: ";
cin >> fName;
cout << "Last Name: ";
cin >> lName;
cout << "Address: ";
cin.clear();
cin.ignore(1, '/n');
getline(cin, address);
cout << "Height (inches): ";
cin >> height;
while (cin.fail()) {
cin.clear();
cin.ignore(256, '/n');
cout << "Height (inches): ";
cin >> height;
}
cout << "Date of Birth: ";
cin.clear();
cin.ignore(1, '/n');
getline(cin, DOB);
cout << "Gender: ";
cin >> gender;
while (cin.fail()) {
cin.clear();
cin.ignore(256, '/n');
cout << "Gender: ";
cin >> gender;
}
if (choice == 2)
{
cout << "ID: ";
cin >> id;
cout << "Classification: ";
cin >> classification;
cout << "GPA: ";
cin >> gpa;
while (cin.fail()) {
cin.clear();
cin.ignore(1, '/n');
cout << "GPA: ";
cin >> gpa;
}
people[i] = new studentType(fName, lName, address, height, DOB, gender, gpa, classification, id);
}
else if (choice == 3)
{
people[i] = new professorType();
cout << "Employee ID: ";
cin.clear();
cin.ignore(1, '/n');
cin >> employeeID;
cout << "Department: ";
cin.clear();
cin.ignore(1, '/n');
getline(cin, department);
cout << "Degree: ";
cin.clear();
cin.ignore(1, '/n');
getline(cin, degree);
people[i] = new professorType(fName, lName, address, height, DOB, gender, employeeID, department, degree);
}
else {
people[i] = new personType(fName, lName, address, height, DOB, gender);
}
cout << endl;
}
system("cls");
for (int i = 0; i < num; i++) {
people[i]->print();
cout << endl;
}
for (int i = 0; i < num; i++)
delete people[i];
delete[] people;
}
I can only print from the personType print function, instead of calling studentType and professor type print functions when needed.

nested do-while loop and while-loop

In this program, choices other than 0 to 4 are all invalid so the user is asked for his/her choice again and again. Then, as choice "1" is entered, the program would perform addition of two numbers. Therefore, it would proceed to ask for the two numbers (x and y) and then print out the calculation result.The user can then choose to perform another calculation. As long as the user does not choose the choice "5" to quit the program, the program would continue to do different calculations chosen by the user.I want to exit the program when choice == 5 . Yet it only returns me "Your choice is invalid, please enter again." Here is the code:
#include <iostream>
using namespace std;
int main()
{
int choice, x, y, z;
do
{
cout << "Math is easy!" << endl << "1. Perform addition" << endl << "2. Perform subtraction" << endl <<
"3. Perform multiplication" << endl << "4. Perform division" << endl << "5. Quit" << endl << "Please enter your choice[1 - 5]:" << endl;
cin >> choice;
while (choice < 1 || choice > 4)
{
cerr << "Your choice is invalid, please enter again.";
cin >> choice;
}
cout << "Please enter x:" << endl;
cin >> x;
cout << "Please enter y:" << endl;
cin >> y;
if (choice == 1)
{
z = x + y;
cout << x << "+" << y << "=" << z << endl;
}
if (choice == 2)
{
z = x - y;
cout << x << "-" << y << "=" << z << endl;
}
if (choice == 3)
{
z = x * y;
cout << x << "*" << y << "=" << z << endl;
}
if (choice == 4)
{
z = x / y;
cout << x << "+" << y << "=" << z << endl;
}
} while (choice != 5);
system("pause");
return 0;
}
How should I do?
Before while loop you can check if(choice == 5) and break;
if(choice == 5)// if choice == 5 break loop. or exit(0);
break;
while (choice < 1 || choice > 4)
{
cerr << "Your choice is invalid, please enter again.";
cin >> choice;
}
.
.
.
.
if (choice == 1)
{
z = x + y;
cout << x << "+" << y << "=" << z << endl;
}
else if (choice == 2)
{
//code
}
else if (choice == 3)
{
//code
}
Use if - elseif instead of using multiple if condition. you can also use switch.

Why is my programme stuck in the if loop?

I am new to C++ and this is like my first program I made and I used Visual C++ 2010 Express.
It is a weight conversion thing. There is an if loop, an else if loop and an else.
Here is the code:
#include <iostream>
using namespace std;
int main() {
float ay,bee;
char char1;
cout << "Welcome to the Ounce To Gram Converter" << endl << "Would you like to convert [O]unces To Grams or [G]rams To Ounces?" << endl;
start:
cin >> char1;
if (char1 = "G" ||"g"){
cout << "How many grams would you like to convert?" << endl;
cin >> bee;
cout << bee << " grams is equal to: " << bee*0.035274 << " ounces." << endl; goto start;
}
else if (char1 = "o"||"O"){
cout << "How many ounces would you like to convert" << endl;
cin >> ay;
cout << ay << " ounces is equal to: " << ay/0.035274 << " grams." << endl; goto start;
}
else{
cout << "Error 365457 The character you entered is to retarded to comprehend" << endl;
goto start;
}
cin.ignore();
cin.get();
return 0;
}
If I enter a "g", it executes this:
if (char1 = "G" ||"g"){
cout << "How many grams would you like to convert?" << endl;
cin >> bee;
cout << bee << " grams is equal to: " << bee*0.035274 << " ounces." << endl; goto start;
}
like it should
However, if I enter an "o", it executes this:
if (char1 = "G" ||"g"){
cout << "How many grams would you like to convert?" << endl;
cin >> bee;
cout << bee << " grams is equal to: " << bee*0.035274 << " ounces." << endl; goto start;
}
Instead of this:
else if (char1 = "o"||"O"){
cout << "How many ounces would you like to convert" << endl;
cin >> ay;
cout << ay << " ounces is equal to: " << ay/0.035274 << " grams." << endl; goto start;
}
Even if I put something random, like "h"
This Happens:
if (char1 = "G" ||"g"){
cout << "How many grams would you like to convert?" << endl;
cin >> bee;
cout << bee << " grams is equal to: " << bee*0.035274 << " ounces." << endl; goto start;
}
Instead of this:
else{
cout << "Error 365457 The character you entered is to retarded to comprehend" << endl;
goto start;
}
Please tell me what I did wrong.
char1 = "o"||"O" will always evaluate to true, because "O" is not null.
You want to use char1 == 'o' || char == 'O' and similar all over your if statements.
Note that = is assignment and == is an equality check. Use == when testing for equality and = when assigning. C and C++ allows you to use = in a check which returns the value of the assignment. This value is not 0, which evaluates to true and thus your if statement executes.

How to make the script rerun?

I know this is very vague but im new to C++. Im making a calculator as a first time project, and what im wanting to do is, if replied to with 'y', make the script rerun from the beginning...basically.
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
int main()
{
cout << "Hello and Welcome to the Test Calculator!\n";
signed char choice;
char resp;
cout << "Choose your problem:\n a)Addition\n b)Subtraction\n c)Multiplication\n d)Division\n e)Square Root\n f)Hypotenuse\n";
scanf ("%c", &choice);
switch (choice)
{
case 'a':
{
int a;
int b;
cout << "Addition\n";
cout << "Please enter a number:\n";
cin >> a;
cout << "Please enter your second number:\n";
cin >> b;
cin.ignore();
int result = a + b;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result;
cin.get();
break;
}
case 'b':
{
int c;
int d;
cout << "Subtraction\n";
cout << "Please enter a number:\n";
cin >> c;
cout << "Please enter your second number:\n";
cin >> d;
cin.ignore();
int result2 = c - d;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result2;
cin.get();
break;
}
case 'c':
{
int e;
int f;
cout << "Multiplication\n";
cout << "Please enter a number:\n";
cin >> e;
cout << "Please enter your second number:\n";
cin >> f;
cin.ignore();
int result3 = e * f;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result3;
cin.get();
break;
}
case 'd':
{
int g;
int h;
cout << "Division\n";
cout << "Please enter a number:\n";
cin >> g;
cout << "Please enter your second number:\n";
cin >> h;
cin.ignore();
int result4 = g / h;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result4;
cin.get();
break;
}
case 'e':
{
int x;
#define square ((x)*(x))
cout << "Square Root\n";
cout << "Please enter a number:\n";
cin >> x;
cin.ignore();
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<square;
cin.get();
break;
}
case 'f':
{
int i;
int j;
cout << "Hypotenuse\n";
cout << "Enter your smaller side:\n";
cin >> i;
cout << "Please enter the longer side:\n";
cin >> j;
cin.get();
int hypotenuse = ((i*i)+(j*j));
cout << "Calculating...\n";
cout << "The hypotenuse is the square root of:\n"<<" "<<hypotenuse;
cin.ignore();
cout << "Would you like to do another problem?\n y)Yes\n n)No\n";
cin >> resp; //this is where im trying to test this at
}
default:
{
cout << " \n";
cout << "Error: Undefined response\n";
cout << "Contact the source programmer for details\n";
}
}
}
If you put the switch into a while loop that checks to see if the char == 'n' it will continue until it finds it.
while(choice != 'n')
{
switch (choice)
{
case 'a':
{
int a;
int b;
cout << "Addition\n";
cout << "Please enter a number:\n";
cin >> a;
cout << "Please enter your second number:\n";
cin >> b;
cin.ignore();
int result = a + b;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result;
cin.get();
break;
}
case 'b':
{
int c;
int d;
cout << "Subtraction\n";
cout << "Please enter a number:\n";
cin >> c;
cout << "Please enter your second number:\n";
cin >> d;
cin.ignore();
int result2 = c - d;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result2;
cin.get();
break;
}
case 'c':
{
int e;
int f;
cout << "Multiplication\n";
cout << "Please enter a number:\n";
cin >> e;
cout << "Please enter your second number:\n";
cin >> f;
cin.ignore();
int result3 = e * f;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result3;
cin.get();
break;
}
case 'd':
{
int g;
int h;
cout << "Division\n";
cout << "Please enter a number:\n";
cin >> g;
cout << "Please enter your second number:\n";
cin >> h;
cin.ignore();
int result4 = g / h;
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<result4;
cin.get();
break;
}
case 'e':
{
int x;
#define square ((x)*(x))
cout << "Square Root\n";
cout << "Please enter a number:\n";
cin >> x;
cin.ignore();
cout << "Calculating...\n";
cout << "Your total is:\n"<<" "<<square;
cin.get();
break;
}
case 'f':
{
int i;
int j;
cout << "Hypotenuse\n";
cout << "Enter your smaller side:\n";
cin >> i;
cout << "Please enter the longer side:\n";
cin >> j;
cin.get();
int hypotenuse = ((i*i)+(j*j));
cout << "Calculating...\n";
cout << "The hypotenuse is the square root of:\n"<<" "<<hypotenuse;
cin.ignore();
cout << "Would you like to do another problem?\n y)Yes\n n)No\n";
cin >> choice; //this is where im trying to test this at
}
}
}
You can add another option to continue calculator. something like this:
while(doContinue == true){
switch{.....}
}
that is, enclose the switching part of code in a while loop. Set doContinue as true at first then change it at the end according to the user input.

Resources