Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to use cin.get() to pause a loop on every time around.
prodAtr.h:
#ifndef PRODATR
#define PRODATR
#include <array>
#include <vector>
#include <string>
extern std::array<std::string, 6> sProductType = { //Array contents here };
extern std::vector<std::vector<double>> nProductRates = {
{ //Array contents here },
{ //Array contents here },
{ //Array contents here },
{ //Array contents here },
{ //Array contents here },
{ //Array contents here }
};
#endif
Wholesale.cpp:
#include "stdafx.h"
#include <iostream>
#include "prodAtr.h"
int ShowProdOpt();
float GetCost();
void CalulateTiers(float, int);
int main()
{
using namespace std;
float fCost = GetCost();
cout << endl;
int nOptChoice = ShowProdOpt();
CalulateTiers(fCost, nOptChoice);
return 0;
}
int ShowProdOpt()
{
using namespace std;
cout << "Please select you product type: " << endl;
for (unsigned int i = 0; i < sProductType.size(); i++)
{
cout << "[" << i + 1 << "]" << sProductType[i] << " ";
}
cout << endl;
int nResult;
cin >> nResult;
return nResult;
}
float GetCost()
{
float fCost;
std::cout << "What is the cost? $";
std::cin >> fCost;
return fCost;
}
void CalulateTiers(float fCost, int nType)
{
using namespace std;
int iii = 0;
while(iii < 10)
{
int jjj = iii + 1;
float fPrice = floor(((nProductRates[nType - 1][iii] * fCost) + fCost) * 100 + 0.5) / 100;
cout << "Tier[" << jjj << "]: $" << fPrice << endl;
cin.get();
iii++;
}
}
VS 2013 log output (minus file loc info):
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
But my result is:
Tier[1]: $1.34
Tier[2]: $1.22
then cin.get() seems to pause and work properly from there.
How do I get cin.get() to pause after every execution of the loop?
I can't give a definitive answer because you have not provided more code, but it seems like there was already something in your cin buffer, so it took that in the get() and continued execution.
Try flushing the buffer before you enter the loop.
SEE: How do I flush the cin buffer?
Ok I added
cin.clear();
cin.ignore();
right before the while loop. Now it works as desired.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
#include <iostream>
using namespace std;
int main()
{
// Local variable declaration:
int a = 10;
// while loop execution
while (a < 20)
{
cout << "value of a: " << a << endl;
a++;
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
// Local variable declaration:
int a = 100;
// while loop execution
while (a > 0)
{
cout << "value of a: " << a << endl;
a--;
}
return 0;
}
Strange indentation. (Now fixed)
But a while loop is based on a condition which means you should initialise the variable a to be 100.
After this use a loop to check while a is greater than 0. Then in the loops body you can output the variable a and decrement the number.
#include <iostream>
using namespace std;
int main()
{
int a = 100;
while (a > 0) {
cout << "value of a: " << a << endl;
a--; // Decrement A
}
}
Another method would be use a for loop
#include <iostream>
using namespace std;
int main()
{
for (int a = 100; a > 0; a--) {
cout << "value of a: " << a << endl;
}
}
These are very simple ways and I'd recommend looking into some books for beginners if you are new to C++ to understand the different syntax of loops.
You can modify your loop like this:
#include<iostream>
#include<ranges>
namespace sv = std::views;
int main()
{
for (int i : sv::iota(1, 101) | sv::reverse)
std::cout << i << "\n";
}
Here's a demo.
Note that this code is only valid from C++20.
So, I'm making a text game. It opens and works fine then will abruptly close with no apparent trigger and open a new instance of itself. After it does this once it does not do it again. If I'm doing other things stupidly I would also like to know this. Heads up that this is a lot of code because I do not know where the problem lies. I tried to cut out the non important bits though. Would also like to know how to read write files in another directory that isn't the root one the exe is in. I am using Code::Blocks to compile. If the header files are important I can include them.
//#libraries
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>
#include "windows.h"
#include "math.h"
#include "time.h"
#include "Dungeon.h"
using namespace std;
//functions
int roomLogic();
void stats();
void options();
void devConsole();
void tutorial();
//Choose Class functions
void chooseClass();
void choosePaladin();
void chooseWarlock();
void chooseRanger();
void chooseWarrior();
void chooseRogue();
//global variables
int textSpeed;
int turns = 0;
bool debug = false;
//Player Stats
//Name and Such
int kills = 0;
int killScore = 0;
int damageDelt = 0;
int damageTaken = 0;
int score = 0;
string name;
string Class;
string race;
//Items
int keys = 0;
int money = 10;
int moneySpent = 0;
//Combat
int att = 10;
int def = 10;
int speed = 10;
int sneak = 10;
int eva = 10;
int perc = 10;
int accuracy = 10;
int health = 100;
int maxHealth = 150;
int mp = 50;
int magicPower = 10;
int main()
{
cout << "WHOLE BUNCH OF INTRO TEXT THAT YOU DO NOT NEED TO READ BECAUSE
THERE IS A LOT" << endl;
Sleep(1000);
//Text Speed Definition
cout << "How do you like your text speed? 'Slow', or 'Fast'?" << endl;
cout << "Type your answer and press ENTER to send" << endl;
string textSpeedInput;
cin >> textSpeedInput;
bool success = false;
//a while statement to get them to say yes no and set a text speed, not
important
cout << "If you have never played the game before and would like a
tutorial, type \n'tutorial' if not type 'no'" << endl;
string tutor;
cin >> tutor;
bool tut = false;
//another while statement thing that I cut out the function literally just
couts
chooseClass();
stats();
roomLogic();
system("PAUSE");
exit(0);
return 0;
}
void chooseClass()
{
cout << "Choice is fun, but randomness can be too, Would you like to
choose your class and race(Yes) or get a random class and race(No)" <<
endl;
string willChoose;
cin >> willChoose;
if(willChoose == "Yes" || willChoose == "yes")
{
cout << "Would you like to be a:\n" << endl;
cout << "Paladin (+3 Defense, -1 Speed)," << endl;
cout << "Warlock (+3 Magic Power, -1 Defense)," << endl;
cout << "Ranger (+2 Accuracy, +1 Perception, +1 Speed, -2 Defense)," <<
endl;
cout << "Warrior (+2 Attack, +1 Defense, -1 Magic Power), or" << endl;
cout << "Rogue (+2 Stealth, +1 Attack, +1 Evasion, +1 Speed, -3
Defense)?" << endl;
bool hasChoosen = false;
cin >> willChoose;
//another cut out while statement
code has broken by this point. I have no clue why. Please help is it an augment I need in my int main or something?
Here is an example read write I use just so you know:
ifstream x_file (".filenamehere.txt"); x_file >> variable to change;
x_file.close();
And to write:
ofstream y_file (".filename.txt"); y_file << thing to write; y_file.close();
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to make a "monster generator" for my console game but have come across what might be a simple issue to fix, the problem is am I am somewhat new to this language.
In my main.cpp I have created a function named, generateMonster():
All generateMonster() does is randomly generate 6 numbers which will become the attributes of this new monster.
generateMonster() successfully creates a monster with random attributes, but why can't I call this new Monster through main.cpp? Whenever I run my build it says:
"error: name was not declared in this scope" ---- and If I change it to Monster::name.returnHp(); then it says "error: name is not a member of 'Monster'". but it is, I just created 'name' with my constructor.
main.cpp
#include <iostream>
#include <windows.h>
#include <time.h>
#include "Character.h"
#include "Monster.h"
using namespace std;
void generateMonster();
int main()
{
Character Bryan = Character(1,2,5,1,10,6);
int choice;
while(true)
{
cin >> choice;
if(choice == 1)
{
generateMonster();
cout << "Monster Stats:\n\n";
cout << "Life Points: " << name.returnHp() << endl ;
cout << "Endurance Chance: " << name.returnEndur() << endl ;
cout << "Dmg: " << name.returnDmg() << endl ;
cout << "Armor: " << name.returnArmor() << endl ;
cout << "Evasion Chance: " << name.returnEvasion() << endl ;
cout << "Agility Chance: " << name.returnAgility() << endl ;
}
}
return 0;
}
void generateMonster()
{
int random ;
int i, j, k, nums[50];
srand(time(NULL)) ;
for( i = 0; i < 50 ; i++)
{
nums[i] = i;
}
for (i = 0; i < 50; i++)
{
j = (rand() % 50) ;
k = nums[i] ; nums[i] = nums[j] ; nums[j] = k ; //switch rands
}
Monster name = Monster(nums[4],nums[45],nums[34],nums[21],nums[37],nums[41]);
//creates an object(Monster class) called name with the random attributes
}
Monster.h
#ifndef MONSTER_H_INCLUDED
#define MONSTER_H_INCLUDED
class Monster
{
private:
float c_hp;
float c_maxHp;
float c_endur;
float c_dmg;
float c_armor;
float c_evade;
float c_agility;
public:
Monster(int hp,int endur, int dmg, int armor, int evasion, int agility);
//constructor
void takeDmg(float dmg);
float returnHp();
float returnMaxHp();
float returnDmg();
float returnArmor();
float returnEndur();
float returnEvasion();
float returnAgility();
};
#endif // MONSTER_H_INCLUDED
Monster.cpp
#include "Monster.h"
#include <iostream>
Monster::Monster(int hp,int endur,int dmg,int armor,int evasion, int agility)
{
c_hp = hp * 50;
c_maxHp = hp * 50;
c_endur = endur * 3;
c_dmg = dmg * 2;
c_armor = armor * 2.5;
c_evade = evasion * 2;
c_agility = agility * 3;
}
void Monster::takeDmg(float dmg)
{
using std::cout;
float trueArmor,trueDmg;
trueArmor = c_armor / 1.60;
trueDmg = dmg - trueArmor;
if(c_hp - trueDmg <= 0)
{
cout << "You have slain the creature!";
c_hp = 0;
}
else
{
c_hp = c_hp - trueDmg;
}
}
//simple return functions
float Monster::returnHp(){return c_hp;}
float Monster::returnMaxHp(){return c_maxHp;}
float Monster::returnDmg(){return c_dmg;}
float Monster::returnArmor(){return c_armor;}
float Monster::returnEndur(){return c_endur;}
float Monster::returnEvasion(){return c_evade;}
float Monster::returnAgility(){return c_agility;}
name does not exist in main. It only exists inside the generateMonster function. To generate a Monster that can be used in main, simply return it from the function. Change the return type to Monster, and add a return statement.
Monster generateMonster()
{
... Everything your function is currently doing ...
// plus this
return name;
}
Then, in main, you can do this:
Monster m = generateMonster();
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to make a program in C++ where the user will input an equation, (e.g.: y = 3x + 6). How would I determine what's a Value, and what's a Character, and where they are?
So from the example, I would know that:
Value 3 is at position stringArray[4]
Value 6 is at position stringArray[9]
Character x is at position stringArray[5]
How would I write this?
When I enter y = 3x in visual studio 2013, it comes up with an error box:
Unhandled exception at 0x77662EEC in Graphmatica_WhatsInDatInput.exe: Microsoft C++ exception: std::invalid_argument at memory location 0x00FAF94C.
but when I enter anything that is not starting with a character, it's fine (e.g. 1 + 3x)
This is my code so far:
#include <iostream>
#include <string>
using namespace std;
int main(){
string Equation;
double dNumber;
cout << ": ";
getline(cin, Equation);
for (int i = 0; i < Equation.size(); i++){
if (isdigit(Equation[i])) {
cout << "Number: ";
dNumber = stod(Equation);
cout << dNumber << endl;
}
else {
if (Equation[i] != ' ') {
cout << "Character" << endl;
}
}
}
cout << endl;
system("pause");
}
Your error is because of this line:
dNumber = stod(Equation);
Its exception documentation says: If no conversion could be performed, an std::invalid_argument exception is thrown.
When you entered a letter, no conversion could be performed and you got the exception.
Secondly, you're trying to convert the entire equation to a double.. If that is the case, what was the point of checking if each index in the string is a digit?
I think you meant to put: stod(to_string(Equation[I])) instead..
You can also create your own conversion functions using the ones already provided for you in C.
#include <iostream>
#include <string>
using namespace std;
inline double strtodouble(char c) noexcept
{
return strtod(&c, NULL);
}
inline double strtodouble(const char* str) noexcept
{
return strtod(str, NULL);
}
inline double strtodouble(const std::string str) noexcept
{
return strtod(str.c_str(), NULL);
}
int main()
{
string Equation;
double dNumber;
cout << ": ";
getline(cin, Equation);
for (int i = 0; i < Equation.size(); i++)
{
if (isdigit(Equation[i]))
{
cout << "Number: ";
dNumber = strtodouble(Equation[i]);
cout << dNumber << endl;
}
else
{
if (Equation[i] != ' ')
{
cout << "Character" << endl;
}
}
}
cout << endl;
system("pause");
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
//Long story short, trying to do a media library, but I am at a 100% Complete loss on why I cannot get this data to work. This is my Main.cpp
#include "CDclass.h"
bool fills = true;//Public Switch to turn on/off autofill of "Data" classes.
bool runner = true;//Public switch that helps with the program functionality(DO NOT EDIT)
void main()
{
int decision;
unsigned int total = 5;
vector<string> titles;
vector<double> time;
string artist;
string name;
titles.resize(total);
time.resize(total);
vector<cdStorage> Data;//A vector of classes
cdStorage newCD;
Data.push_back(newCD);
Data.push_back(newCD);
Data.push_back(newCD);//This was used as a sizing test and it works.
cdStorage::cdStorage(total);
//I used this to loop without restarting main.
while(runner == true)
{
if(fills == true)//Autofill to get the program running
{
artist = "Bunny";
name = "Bread";
for(unsigned int x = 0; x < Data.size(); x++)
{
cdStorage::cdStorage(total);
Data[x].setNewArtist(artist);
Data[x].setNewName(name);
for(unsigned int y = 0; y < total; y++)
{
titles[y] = "TestfieldBanana!";
time[y] = 12.13;
Data[x].setNewTitles(y, titles[y]);
Data[x].setNewTime(y, time[y]);
}
}
fills = false;
}
cout << Data[0].getNewArtist() << endl;
cout << "*******************" << endl <<
"*Media Awesomsauce*" << endl <<
"*******************" << "\n\n" <<
"********************" << endl <<
"* 1: Check Library *" << endl <<
"* 2: Add CD *" << endl <<
"* 3: Delete CD *" << endl <<
"* 4: Exit Program *" << endl <<
"********************" << "\n\n" <<
"Decision:_";
cin >> decision;
//The majority of all of this is very self explanatory.
if(decision == 1)
{
for(unsigned int x = 0; x < Data.size(); x++)
{
cdStorage::cdStorage(total);
cout << Data[x].getNewName() << "\t";
cout << Data[x].getNewArtist() << "\t";
for(unsigned int y = 0; y < total; y++)
{
//int length = Data[x].getNewName().length();
cout << "\t\t\t" << Data[x].getNewTitles(y);
cout << "\t" << Data[x].getNewTime(y) << endl;
}
}
}else if(decision == 2)
{
Data.push_back(newCD);
system("CLS");
cout << "What is the name of the CD: ";
cin >> name;
cout << "\nWhat is the name of the Artist: ";
cin >> artist;
cout << "\nHow many songs are there: ";
cin >> total;
cdStorage::cdStorage(total);
titles.resize(total);
time.resize(total);
Data[Data.size()].setNewName(name);
Data[Data.size()].setNewArtist(artist);
cout << "What are the song titles and lengths:\n";
for(unsigned int x = 0; x < total; x++)
{
cout << "Title " << x+1 << ": ";
getline (cin, titles[x]);
cout << "Length(Example: 3.36 for 3 mins and 36 seconds): ";
cin >> time[x];
cout << endl;
Data[Data.size()].setNewTitles(x, titles[x]);
Data[Data.size()].setNewTime(x, time[x]);
}
}else if(decision == 3)
{
}else if(decision == 4)
{
runner = false;
}else
{
system("CLS");
cout << "Error: You must choose a number between 1-5...\n\n";
system("pause");
system("CLS");
}
}
}
//This is my CDWorks.cpp
#include "CDclass.h"
//Constructor
cdStorage::cdStorage(){};
//Overloaded Constructor
cdStorage::cdStorage(unsigned int theTotal)
{
newTotal = theTotal;
newTitles.resize(newTotal);
newTime.resize(newTotal);
}
//Accessors
unsigned int cdStorage::getNewTotal() const
{
return newTotal;
}
string cdStorage::getNewTitles(unsigned int x) const
{
return newTitles[x];
}
double cdStorage::getNewTime(unsigned int x) const
{
return newTime[x];
}
string cdStorage::getNewArtist() const
{
return newArtist;
}
string cdStorage::getNewName() const
{
return newName;
}
//Mutators
void cdStorage::setNewTotal(unsigned int theTotal)
{
newTotal = theTotal;
}
void cdStorage::setNewTitles(unsigned int x, string theTitle)
{
newTitles[x] = theTitle;
}
void cdStorage::setNewTime(unsigned int x, double theTime)
{
newTime[x] = theTime;
}
void cdStorage::setNewArtist(string theArtist)
{
newArtist = theArtist;
}
void cdStorage::setNewName(string theName)
{
newName = theName;
}
//Destructor
cdStorage::~cdStorage(){}
//This is my CDClass.h
#include <iostream>
#include <string>
#include <vector>
using namespace std;
#ifndef CDCLASS_H
#define CDCLASS_H
class cdStorage
{
private:
unsigned int newTotal;
vector<string> newTitles;
vector<double> newTime;
string newArtist;
string newName;
public:
//Constructor
cdStorage();
//Overloaded Constructor
cdStorage(unsigned int);
//Destructor
~cdStorage();
//Accessors
unsigned int getNewTotal() const;
string getNewTitles(unsigned int) const;//The integer is to track which element needs returned.
double getNewTime(unsigned int) const;
string getNewArtist() const;
string getNewName() const;
//Mutators
void setNewTotal(unsigned int);
void setNewTitles(unsigned int, string);
void setNewTime(unsigned int, double);
void setNewArtist(string);
void setNewName(string);
};
#endif
Data[Data.size()] is accessing outside the vector Data, which is undefined behaviour, so anything can happen.
Also, I don't know what you think repeatedly calling cdStorage::cdStorage(total); does, but it doesn't do anything except create a new (anonymous) object that is immediately thrown away.
All the cdStorages you have created were created using the default (parameterless) constructor, which leaves newTotal totally uninitialized, and the vectors are both empty. You can't modify them by calling a constructor afterwards (I suspect that is what yo're trying to accomplish).
Since the vectors are empty, when you say e.g. newTitles[x] = theTitle;, you're accessing invalid memory, which means that your program, again, has undefined behaviour.
It's very difficult to say whether these are the cause of your problems, but you should probably fix them first before you go on.
You should probably review the chapter on constructors and instance creation in your Fine Book.
Data[Data.size()].setNewName(name);
This accesses past the end of the vector, it only has Data.size() elements, starting from zero. This is undefined behaviour and probably causing the problem.
It may not be the problem, but as you haven't said where the error happens it's hard to know. You have the failing program, you should be able to debug it and say where it blows up ... you've had three days to learn to use a debugger!
Until you know what you're doing I suggest you stop using [x] to access vectors and switch to using the at(x) function, which does the same thing but checks that x is a valid index and not larger than the vector's size. If you'd done that then you'd have got an exception at the first problem, instead of undefined behaviour and a stack overflow.
There are a number of other issues...
Put your include guards at the top of the file, not after other headers.
Never put using namespace at namespace scope in a header.
You keep doing this:
cdStorage::cdStorage(total);
What's that supposed to do and why do you keep doing it?
You should use member initializers in constructors instead of altering them in the constructor body:
cdStorage::cdStorage(unsigned int theTotal)
{
newTotal = theTotal;
newTitles.resize(newTotal);
newTime.resize(newTotal);
}
i.e. do this instead:
cdStorage::cdStorage(unsigned int theTotal)
: newTotal(theTotal), newTitles(theTotal), newTime(theTotal)
{ }