How do I use cin in a while loop? - c++

I'm trying to get the user to input their name(s) using a while loop with an array and cin, but after the last person's name is input, the program crashes instead of moving on. Is there a way to fix this, or do I need to completely change up the code? I'm also fairly new to c++, so can any answers be given as simply as possible?
#include <iostream>
#include <string>
using namespace std;
int main()
{
unsigned int numberofplayers;
number://loop back here if more than 4 players
cout << "Number of players: ";
cin >> numberofplayers;
if(numberofplayers > 4 || numberofplayers < 1){
cout << "Invalid number, please enter a number from 1 to 4." << endl;
goto number;
}
string name[numberofplayers];
cout << "Enter your name" << endl;
int a = 1;
while(a < numberofplayers + 1){
cout << "Player " << a << ": ";
cin >> name[a];
cout << "Hello, " << name[a] << "." << endl;
a++;
}
}

You would probably facing array index out of bound, so Change you while loop to this and set a=0 to fill from 0th index.
while(a < numberofplayers){
}

Your last iteration exceeds the size of the array. You need to change it to
while(a < numberofplayers)
also, on another note, the keyword goto isn't used much anymore. I would suggest using a while there also like
while(true){
cout<<"number of players";
cin>>numberofplayers
if(numberofplayers is valid input){
break;
}
cout<<"bad input";
}
There is a question on stackoverflow discussing the use of goto extensively here:
GOTO still considered harmful?

Related

Endless loop in c++

I am currently learning c++ and I have come to a strange behavior at my code:
#include<iostream>
using namespace std;
int main(){
int input;
int counter = 0;
while (input != 0 && counter <= 100){
cout << "-----------\n";
cout << "0 = Get Out!\nEverything else will be displayed!\nPlease enter a number: ";
cin >> input;
cout << "The number: " << input << "\n";
counter++;
}
return 0;
}
This Program itself works fine, but when I am typing a number as input, which is at least the maximum of the integer datatype + 1, then this loop will be endless (I programmed a stop after 100 loops) and I cannot really explain this to me. In other languages the program just crashes or gives out an error, because the allocated storage is just not high enough for the data typed in, what is logic and I understand that, but why do the loop gets endless here, that does not make any sense, because I cannot do any inputs after this happens, it just keeps doing the loop with the value (integer maxnumber, in my book stands, that the maxnumber can vary from system to system, so I do not type my number) endlessely and I cannot do anything, but watch my console getting flooded with the same 4 lines.
I would really appreciate, if somebody could explain this phenomena to me, I mean it is not crucial, but it catched my interest anyways.
Your input variable needs to be initialized because you check its value in the while (input != 0 && counter <= 100){ before assigning the input value.
Undefined Behaviour is typical in C++ when exceeding data type limits. These are some common UB.
This post contains the "solution" to your problem
How about the following? Is this what you want?
#include<iostream>
using namespace std;
int main(){
int input;
int counter = 0;
cout << "0 = Get Out!\nEverything else will be displayed!\nPlease enter a number: ";
cin >> input;
cout << "The number: " << input << "\n";
while (input != 0 && counter <= 100){
cout << "Please enter the next number: ";
cin >> input;
cout << "The number: " << input << "\n";
counter++;
}
}

How do I make an if statement that repeats itself if the requirements are still not met?

Here's my code.
#include <iostream>
using namespace std;
int main()
{
int i = 0;
int players;
int silenceAmount;
int bleedAmount;
int bleedDays;
int playersAlive;
int playersDead;
int playersAllowed = 6;
cout << "How many players are playing (can only be " << playersAllowed << ")? ";
cin >> players;
if (players > playersAllowed) (
cout << "There an only be " << playersAllowed << " players. Please select another number. ");
cin >> players;
cout << "There are " << players << " players.\n\n";
return 0;
}
this works for only one time and I want it to work until it gets a number less than or equal to 6.
Repeating if statements are generally done as a while loop. In your code, when you have
if (players > playersAllowed)
You should simply change it do
while (players > playersAllowed)
Also, while I'm at it, the syntax you have for your if statement is not correct for what you are trying to do. You should replace ( and ) by { and } respectively. Also, the ending bracket is in the incorrect place.
In the end, your loop would be something like this:
while (players > playersAllowed) {
cout << "There can only be " << playersAllowed << " players. Please select another number: ";
cin >> players;
}
Note that this doesn't take into account someone entering jfksdjfs for a number.

Simple Number Guessing Game. C++

I've been trying to make a simple game where the computer generates a random number and you try to guess it. It also stores the amount of guesses you make "tries".
However, when I run the program, it simply prints: "Let's play a game. I'll think of a number 1-100. Try to guess it."
Here's my code:
#include <iostream>
int main()
{
using namespace std;
int the_number;
int guess;
int tries;
the_number = rand() % 101 + 1;
cout << "Let's play a game!";
cout << "I will think of a number 1-100. Try to guess it.";
cout << endl;
cin >> guess;
for (tries = 0; tries++;)
{
if (guess == the_number)
{
cout << "You guessed it!";
cout << "And it only took you: " << tries;
}
else if (guess < the_number)
{
cout << "Higher";
tries++;
}
else if (guess > the_number)
{
cout << "Lower";
tries++;
}
else
cout << "That's not even in range!";
return 0;
}
}
I don't understand why this doesn't work, could someone explain why not?
The reason your program does not print anything after "Let's play a game. I'll think of a number 1-100. Try to guess it." is the way you have written your for loop.
for ( tries = 0; tries++; )
breaks out of the loop without doing anything because tries++ evaluates to 0.
Also, for your program to work correctly, you need to add more code to read guesses. Something like the code below, should work.
for (tries = 0; ; tries++)
{
if (guess == the_number)
{
cout << "You guessed it!";
cout << "And it only took you " << tries << " tries.\n";
break;
}
else if (guess < the_number)
{
cout << "Higher";
cin >> guess;
}
else if (guess > the_number)
{
cout << "Lower";
cin >> guess;
}
}
You can define a couple of variables that will make your code more understandable, something like this :
#include <iostream>
using namespace std;
int main()
{char EndGame = 'N';
int MyNumber = 150 , playerguess;
cout << "I have a number between 1 and 100.\nCan you guess my number ??\nPlease type your first guess.\n?" << endl;
do{
cin >> playerguess;
if (playerguess > MyNumber) {
cout << " Too High. Try again." << endl;
}
else if (playerguess == MyNumber) {
cout << "Excellent ! You Got It ! \n If you want to exit press Y" << endl;
cin >> EndGame;
break;
}
else {
cout << " Too Low. Try again." << endl;
}
} while (1);
return 0;
}
This will make the number equal to 150. Each time the user inputs a value, the console will determine whether it is higher, lower or equal to the number.
If you want instead to make it a random number each time, you can simply use the <random> library and use the module operator with a number like 100 or 101. Then, you can add 1; this will generate only positive integers.
You should use while loop here, not for:
while (the_number != guess)
{
//
//
}
And try using the new <random> header instead of rand() function:
#include <random>
std::random_device rd;
std::default_random_engine engine(rd());
std::uniform_int_distribution<int> uniform_dist(1, 100);
the_number = uniform_dist(engine);
Your for loop is wrong (it needs 3 things: initialization, check condition and the todo step after each loop.
For example:
for (tries = 0; tries < 5; tries++)
Also you loop the guessing part, but you forget to ask the user for a new number. I would suggest to move the cin << guess into the for loop.

C++ Array parameters and const value

I do not get arrays, Im sure there are easier ways to make this program but I must do it the teacher's way and I am lost.
This is the assigment:
I do not get how I should go about these arrays. most confusing thing I seen by far.
What I would like is a guide or help on how i should program these arrays or how I should program arrays period. Not asking to do the rest for me, I already know how to do most of this, its just the arrays I like to know how to do.
This is my current program:
#include<iostream>
using namespace std;
void getPoints(int pPossible[], double pEarned[], int numItems, int limit);
int sumArray(double
void getpoints(int pPossible[], double pEarned[], int numItems, int limit)
{
int count;
while (limit == limit)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numbItems > limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
count=1;
for(count=1; count<numItems; count++)
cout << "Enter points then points possible for Item " << count << ": ";
cin << pEarned[count] << pPossible[count];
return 0;
}
C++ array indexes are zero-based, so you should use zero for the initial value in the for loop. Also, you're missing the braces for the for loop body; as it is, it will run the cout line numItem-1 times and the cin line just once.
Another thing: the operators in the for's cin line should be >>, not <<. You want input here, not output.
Finally, like #ebyrob said, make numItems a reference parameter (it would be clearer for the caller to use a pointer instead, but the assignment asked for a reference parameter).
void getpoints(int pPossible[], double pEarned[], int& numItems, int limit)
{
//Read number of items
while (true)
{
cout << "Input grade points for a category in the gradebook: " << endl
<< "How many items available in the category?: ";
cin >> numItems;
cout << endl;
if(numItems >= limit)
{
cout << "The Value exceeds the maximum number of items." << endl;
continue;
}
break;
}
//Read earned and possible for each item
for(int count=0; count<numItems; count++)
{
cout << "Enter points then points possible for Item " << count << ": ";
cin >> pEarned[count] >> pPossible[count];
}
return 0;
}

How can I use 2D array in C++ using Visual Studio?

I'm new to this site and programming in C++ language this semester.
I have been really trying for 2 days and have asked classmates but they do not know either. A classmate said to use the 2D arrays but I don't know what that is and my professor has not gone over 2D arrays.
I am stuck and would really appreciate help.
The input file contains this:
Plain_Egg 1.45
Bacon_and_Egg 2.45
Muffin 0.99
French_Toast 1.99
Fruit_Basket 2.49
Cereal 0.69
Coffee 0.50
Tea 0.75
idk how to display all the "users" orders
Basically a receipt, like he orders this and how many, then ask "u want anything else?", then take the order number and how many again, THEN at the end give back a receipt that looks like this
bacon_and_eggs $2.45
Muffin $0.99
Coffee $0.50
Tax $0.20
Amount Due $4.14
Here is my code:
// Libraries
#include <iostream>
#include <string>
#include <iomanip>
#include <fstream>
#include <cmath>
using namespace std;
//structures
struct menuItemType {
string itemName;
double itemCost;
};
// Prototypes
void header();
void readData(menuItemType menu[]);
void Display(menuItemType menu[]);
int main() {
header();
menuItemType menu [8];
readData(menu);
Display(menu);
//system("pause");
return 0;
}
void header() {
char c= 61;
for (int i=0; i < 64; i++) {
cout << c;
}
cout << c << endl;
cout << endl;
cout << "Breakfast Menu" <<endl;
for (int i=0; i < 64; i++) {
cout << c;
}
cout << "" << c << endl;
cout << endl;
}
void readData(menuItemType item[]) {
int i=0;
ifstream in;
in.open("input.txt");
cout << fixed << setprecision(2);
while(!in.eof()) {
in >> item[i].itemName >> item[i].itemCost;
++i;
}
}
void Display(menuItemType item[]) {
int choice = 0, quantity = 0;
double total = 0.0, totalF = 0.0, tax = 0.0;
char exit = 'y';
int j = 1, z = 1, i = 1;
//the Menu
for (int i=0; i<8; i++){
cout << j << ". " << setw(18) << left << item[i].itemName << "$" << setw(10) << item[i].itemCost << endl;
j++;
}
cout << endl;
while(exit == 'y' || exit == 'Y') {
cout << "Please Enter your Selection or 0 to Exit : ";
cin >> choice;
if(cin.fail()) {
cout << "*******Invalid selection*******" << endl;
cin.clear();
cin.ignore(1000,'\n');
} else if (choice==0) {break; }
else {
cout<< "Enter Quantity: ";
cin>> quantity;
if (quantity==0) { break;}
else {
choice--;
total += (quantity * item[choice].itemCost);
tax = (total * .05);
totalF = total + tax;
cout << endl;
}
cout << endl;
cout << "======================================================" << endl;
cout << item[choice].itemName << "\t\t" << item[choice].itemCost << endl;
cout << "======================================================" << endl;
cout << "Do you want to continue (Y/N): ";
cin >> exit;
}
}
}
First off, you don't need a two dimensional array for this! You already have a one dimensional array of a suitable structure, as far as I can tell: Something which stores the name of the object and its price. What is somewhat missing is how many objects are currently in the array and how much space it has. If you want to go with the content of the entire array, make sure that you objects are correctly initialized, e.g., that the names are empty (this happens automatically, actually) and that the prices are zero (this does not).
I'm not sure if it is a copy&paste errors but the headers are incorrectly included. The include directives should look something like this:
#include <iostream>
The actual loop reading the values doesn't really work: You always need to check that the input was successful after you tried to read! Also, using eof() for checking that the loop ends is wrong (I don't know where people pick this up from; any book recommending the use of eof() for checking input loops is only useful for burning). The loop should look something like this:
while (i < ArraySize && in >> item[i].itemName >> item[i].itemCost)
++i;
}
This also fixes the potential boundary overrun in case there is more input than the array can consume. You might want to consider using a std::vector<Item> instead: this class keeps track of how many elements there are and you can append new elements as needed.
Note that you didn't quite say what you are stuck with: You'd need to come up with a clearer description of what your actual problem is. The above is just correcting existing errors and readjusting the direction to look into (i.e., forget about two dimensional arrays for now).