Output file to .txt and console c++ - loops

I have been trying to figure out how to mirror the programs output to a .txt file as well as the console. I am relatively new to this, so I'm lost.. Please help, here is what I have so far.
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>
using namespace std;
bool isPrime (int);
int main ()
{
int numbers;
ifstream inputFile;
//open the file
inputFile.open("22.txt");
//output to file
ofstream outFile;
outFile.open("PrimeNumbers.txt");
while(inputFile >> numbers)
if(isPrime(numbers))
outFile << numbers << endl;
cout << numbers << " is a prime number." << endl;
} //end of main function
//function formula
bool isPrime (int num)
{
int count=0;
for (int numb=2;
numb<=num/2;
numb++)
{
if(num%numb==0)
count++;
}
if (count>0)
return false;
else
return true;
}

One error that stands out to me is:
while(inputFile >> numbers)
if(isPrime(numbers))
outFile << numbers << endl;
cout << numbers << " is a prime number." << endl;
You don't have any blocks (defined by curly brackets) so this snippet is equivalent to:
while(inputFile >> numbers)
{
if(isPrime(numbers))
{
outFile << numbers << endl;
}
cout << numbers << " is a prime number." << endl;
}
See how the "cout" statement isn't affected by the condition? What you wanted to write is:
while(inputFile >> numbers)
{
if(isPrime(numbers))
{
outFile << numbers << endl;
cout << numbers << " is a prime number." << endl;
}
}
(Also, see my comment underneath your question requesting a more precise definition of the problem if you want more help)

Related

if loop inside a void function not working

So I'm doing a program for a class, and I set up an if loop inside a function definition to set parameters for entries. I'm supposed to be taking inputs between 0 and 10 only. But it's only catching the numbers that are less than 0. It won't catch the numbers larger than 10.
int main()
{
float score1, score2, score3, score4, score5;
cout << endl;
cout << "Judge #1: " << endl;
getJudgeData(score1);
cout << "Judge #2: " << endl;
getJudgeData(score2);
cout << "Judge #3: " << endl;
getJudgeData(score3);
cout << "Score #4: " << endl;
getJudgeData(score4);
cout << "Score #5: " << endl;
getJudgeData(score5);
calcScore(score1, score2, score3, score4, score5);
return 0;
}
void getJudgeData (float &score)
{
cin >> score;
if(score < 0 || score > 10)
{
cout << "Error: Please enter a score between 0 and 10." << endl;
cin >> score;
}
}
Please change the if condition in your getJudgeData function into a while loop:
void getJudgeData (float &score)
{
cin >> score;
while (score < 0 || score > 10)
{
cout << "Error: Please enter a score between 0 and 10." << endl;
cin >> score;
}
}
Otherwise the condition will be only checked once, means for the first input of every judge. This isn't intended, if I understood your issue correctly.
Please find more information regarding the while loop here:
while

check order of array in c, using recursion and malloc [duplicate]

I am trying to debug a recursive function used to validate user input and return a value when the input is OK. The function looks like this:
double load_price()
{
double price;
Goods * tempGd = new Goods();
cin >> price;
while (!cin)
{
cin.clear();
#undef max
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << endl;
cout << "You didn't enter a number. Do so, please: ";
cin >> price;
} // endwhile
if (!tempGd->set_price(price))
{
cout << endl;
cout << "The price " << red << "must not" << white << " be negative." << endl;
cout << "Please, insert a new price: ";
load_price();
}
else
{
delete tempGd;
return price;
}
}
The method set_price() of Goods class looks as follows
bool Goods::set_price(double price)
{
if (price> 0)
{
priceSingle_ = price;
priceTotal_ = price* amount_;
return true;
}
return false;
}
I tried drawing the problem on a paper but all my diagrams seem to look the way my function already looks like. I think there are some problems with returns, but I do not know where.
Help would be greatly appreciated.
You're not using the return value of the recursive call. You need to do:
return load_price();
Who talked you into using recursion for that problem?
#undef max
double load_price()
{
for(;;) {
double price;
cin >> price;
if (!cin)
{
cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << endl;
cout << "You didn't enter a number. Do so, please: ";
continue;
}
if (!Goods().set_price(price))
{
cout << endl;
cout << "The price " << red << "must not" << white << " be negative." << endl;
cout << "Please, insert a new price: ";
continue;
}
return price;
}
}

C++ How to Increment Int Variable From String Array Element

I'm wondering if there is a way to increment an int variable when a specific string array element is called? I'm working on a project for fun and have run into a roadblock. The goal of my project is to have a program that determines what genres of electronic music the user likes. The program will present two DJ's and ask the user which one they prefer or allow them to select neither. Each DJ will have up to three genres that they mainly specialize in, and I have created int variables for each (with all being set to 0). Once a user selects a DJ, I want points to be assigned to each genre variable in which the DJ is associated with. I'm unsure of how to set up this rule as everything I have attempted so far has failed (two example attempts are commented out in the code). Eventually my plan is to develop logic to have the DJ's randomly selected, however I need to have the genre tally allocation set up first. Is there any way this can be done? Any help would be greatly appreciated. Cheers!
###include "stdafx.h"
###include < iostream>
###include < iomanip>
###include < string>
###include < array>
###using namespace std;
int main()
{
cout << "Hello! This program is designed to figure out what Electronic Music you like based on artists presented and the answers you choose...\n" << endl;
cout << "When you are ready to begin press \"Enter\"..." << endl;
getchar();
int bigRoom = 0;
int deepHouse = 0;
int drumBass = 0;
int dubstep = 0;
int electroHouse = 0;
int futureHouse = 0;
int hardDance = 0;
int house = 0;
int progressiveHouse = 0;
int techno = 0;
int trance = 0;
int trap = 0;
string textArray[5]{ "DeadMau5", "Armin Van Buuren", "Avicii", "Ferry Corsten", "Kaskade"};
string answer;
cout << "Select the DJ you prefer by number. Otherwise select 3 if you don't know them. " << endl; //Haven't coded option 3 yet.
cout << "1 - " << textArray[1] << endl;
cout << "2 - " << textArray[2] << endl;
cin >> answer;
/*
if (textArray[1]) {
++trance;
}
for (textArray[1]) {
++trance;
}
*/
if (answer == "1") {
cout << "You have selected: " << textArray[1] << endl;
}
else if (answer == "2") {
cout << "You have selected: " << textArray[2] << endl;
}
//cout << trance << endl;
}
You can increment each tally once the user has selected a DJ:
if (answer == "1") {
cout << "You have selected: " << textArray[1] << endl;
++trance;
// ++ ohter genres you want to increment
}
else if (answer == "2") {
cout << "You have selected: " << textArray[2] << endl;
++trance;
// ++ ohter genres you want to increment
}

cstring << no operator found which takes a right-handed operand of type 'std::string'

I have an assignment in which we are supposed to use cstrings instead of strings. The problem lies in the << operands in three out of the five cout statements. Can anybody help me figure out how to get the operand errors to go away? The code is posted below. The error locations are listed in bold! Thanks!
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
int main()
{
int strLength, wPointer;
string custNumber, year, workOrderNumber;
string workOrder = "91800w940770";
strLength = workOrder.length();
wPointer = workOrder.find('w', 0);
custNumber.assign(workOrder, 0, wPointer);
year.assign(workOrder, wPointer + 1, 2);
workOrderNumber.assign(workOrder, wPointer + 3, strLength);
cout << "The length is " << strLength << endl;
cout << "The location of the w is " << wPointer << endl;
std::cout << "The customer number is " **<<** custNumber << std::endl;
cout << "The year of the order is " **<<** year << endl;
cout << "The order number is " **<<** workOrderNumber << endl;
system("pause");
return 0;
}
custNumber, year and workOrderNumber are strings.
Include <string> to use them with << operator.
The library "<<" function won't work on std::strings. You could create your own function that would output the characters of the string one char at a time

Program wont change array value

(Win32 console app) Ok so i know its a bit to look at, but ive added as many helpful comments that i could think of, im sort of new to coding so if this is a quick fix i apologize for taking your time, ive searched high and low and cant figure this out. So, it prompts the user for a name, that works, then for a race, that works, but under the display function, it fails to show the updated stats (updated by which race you choose). although sometimes it will work with the hp/maxHP but not att nor def. im not sure if its something to do with the scope or what, ive tried all i know :/ thanks for your time and help :)
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int stats[6] = {1, 10, 10, 1, 0, 0};//life(0), maxHp(1), hp(2), att(3), def(4), gold(5)
void shop();//goes to the shop
void fight();//goes to fighting area
void sleep();//refills hp
void welcome();//establishes name
void display();//hud
void whereTo();//travel selection
void doRace();//establishes name
void human();//race#1
void orc();//race#2
void dwarf();//race#3
string name;//variable for name
//Main
int main()
{
welcome();
doRace();
while(stats[0]==1)
{
whereTo();
cout << stats[1];
system("PAUSE");
}
cout << "If you are reading this, you have DIED!\n";
system("PAUSE");
return 0;
}
void shop()
{
display();
cout << "To-be shoping area.\n";
system("PAUSE");
}
void fight()
{
display();
cout << "To-be fighting area.\n";
system("PAUSE");
}
void sleep()
{
display();
cout << "You rest completely..." << endl;
stats[2] = stats[1];
system("PAUSE");
}
void whereTo()
{
display();
cout << "Where would you like to go?\n\n Shop(1)\n Fight(2)\n Sleep(3)\n";
int place;
cin >> place;
system("CLS");
if(place==1)
{
shop();
}
else if(place==2)
{
fight();
}
else if(place==3)
{
sleep();
}
else
{
cout << "Please enter 1, 2, or 3.";
system("PAUSE");
system("CLS");
whereTo();
}
}
void display()//Header to everything
{
system("CLS");
cout << name << " HP: " << stats[2] << "/" << stats[1] << " Att: " << stats[3] << " Def: " << stats[5] << " Gold:" << stats[5] << endl << endl;
}
void welcome()//runs once, establishes name in beginning
{
cout << "Welcome to my first RPG Program\n\n";
system("PAUSE");
system("CLS");
cout << "Enter your character's name\n\n";
cin >> name;
system("CLS");
}
void doRace()//choosing a race at the start
{
cout << "What Race would you like to be?\n\n\n 1)Human (More Attack and Defense)\n\n 2)Orc (More Hp and Attack)\n\n 3)Dwarf (More HP and Defense)\n\n";
int race;
cin >> race;
if(race==1)
{
human();
cout << "You chose Human!" << endl;
system("PAUSE");
}
else if(race==2)
{
orc();
cout << "You chose Orc!" << endl;
system("PAUSE");
}
else if(race==3)
{
dwarf();
cout << "You chose Dwarf!" << endl;
system("PAUSE");
}
else
{
cout << "Please enter 1, 2, or 3.";
system("pause");
system("CLS");
doRace();
}
}
void dwarf()//sets the initial stats of the character based off of race selection
{
stats[1] = stats[1] + 3;//maxHp
stats[2] = stats[2] + 3;//hp
stats[4] = stats[4] + 2;//def
}
void human()//sets the initial stats of the character based off of race selection
{
stats[3] = stats[3] + 2;//att
stats[4] = stats[4] + 2;//def
}
void orc()//sets the initial stats of the character based off of race selection
{
stats[1] = stats[1] + 3;//maxHp
stats[2] = stats[2] + 3;//hp
stats[3] = stats[3] + 2;//att
}
You are using the wrong index for def. It should be 4
Def: " << stats[5].

Resources