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 7 years ago.
Improve this question
I am making a game and I want it to only run if player consents by saying PLAY but it won't run. Here is my code:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int balance = 500;
char start;
cout << "Welcome to Vegas! Your starting balance is 500 dollars lets play! " << endl;
cout << "Type PLAY to begin !" <<endl;
cin >> start;
while(start == 'PLAY') {
cout << "Your beginning numbers are!" << endl;
}
}
A char is a single character, like 'P'. If you expect the user to enter a full string, you want to use std::string. Additionally, you probably want to simply check if the user entered the string you wanted - not while - unless you want to prompt again at the end of your game.
Corrected code would be:
std::string start;
// ...
std::cin >> start;
if (start == "PLAY") {
// play the game
}
start is a char and not an array of char. You are only storing one letter in start
Change that, and also change 'PLAY' to "PLAY". Consider using a std::string instead.
Example of what you can do:
int balance = 500;
char start[256];
bool started = false;
cout << "Welcome to Vegas! Your starting balance is 500 dollars lets play! " << endl;
cout << "Type PLAY to begin !" <<endl;
cin >> start;
if (!strcmp(start, "PLAY")) { // #include <cstring>
started = true;
}
while(started) {
cout << "Your beginning numbers are!" << endl;
}
Or with using std::string:
int balance = 500;
string start;
bool started = false;
cout << "Welcome to Vegas! Your starting balance is 500 dollars lets play! " << endl;
cout << "Type PLAY to begin !" <<endl;
cin >> start;
if (start == "PLAY") {
started = true;
}
while(started) {
cout << "Your beginning numbers are!" << endl;
}
change char start; to char start[100];
and while(start == 'PLAY') to while(start == 'PLAY')
Here is the final code
int balance = 500;
char start[100];
cout << "Welcome to Vegas! Your starting balance is 500 dollars lets play! "<< endl;
cout << "Type PLAY to begin !" <<endl;
cin >> start;
while(!strcmp(start,"PLAY")) {
cout << "Your beginning numbers are!" << endl;
}
You are trying to take in as input a string, but storing using a character.
use
char start[SIZE];
Also are u sure comparing with 'PLAY' is being done in the right way? Use " for strings. Better to use string functions.
Related
so I have been learning C++ and was working on a monkey see monkey do program and i managed to get the first input working but the second input it just skips straight over it, i have no clue why and any help would be apreciated.
#include <iostream>
#include <string>
using namespace std;
char monkey_1;
char monkey_2;
int msmd()
{
cout << "monkey one:"; cout << endl;
cin >> monkey_1;
system("cls");
cout << "monkey two:"; cout << endl;
cin.clear();
cin >> monkey_2;
cout << "waiting"; cout << endl;
if (monkey_1 == monkey_2)
{
cout << "both monkeys are happy."; cout << endl;
}
else
{
cout << "the monkeys are upest."; cout << endl;
}
return 0;
}
void main()
{
msmd();
}
Do you intent to only get a single character from the input as the monkeys are of type char? If not, change them to string, otherwise it will only assign a single character per cin.
If you want to input a sentence, cin also splits on spaces, so if you enter "something else", the first cin will assign something to monkey_1, and the second cin will automatically assign else to monkey_2.
To get around this you can use getLine(cin,monkey_x).
There are two point needs to be modified.
char monkey_1 and mokeny_2 should be declared as string for get more than 1 character.
void main need to be changed as int main.
This question already has answers here:
std::cin input with spaces?
(8 answers)
Closed 3 years ago.
so I'm working on a homework problem for my CS175 C++ course. We have a homework assignment where we have to make a shorting hat, kinda like what's in Harry Potter. I've got 99% of the code down, however the thing that is tripping me up is how to read in a string with white space.
We need to be able to input full names so obviously just using std::cin >> won't work. The problem is that I can't seem to get any of the methods to work that I've tried so far.
This is my code:
#include <iostream>
#include <string>
int main()
{
int NumStudents;
std::string NameStudents;
int StartValue;
int House;
std::string HouseName;
int NumCornfolk = 0;
int NumEsophagus = 0;
int NumBob = 0;
//How many students are there?
std::cout << "How many students are there? \n";
std::cin >> NumStudents;
for (StartValue = 0; StartValue < NumStudents; StartValue++) {
std::cout << "Please enter the name of the next student. \n";
std::cin >> NameStudents; \\**THE PROBLEM IS HERE**
//Assings the House
House = rand() % 100 + 1;
if (House <= 19) {
HouseName = "Cornfolk! \n";
NumCornfolk++;
}
else if (House > 19 && House < 50) {
HouseName = "Esophagus! \n";
NumEsophagus++;
}
else if (House >= 50) {
HouseName = "Bob! \n";
NumBob++;
}
std::cout << NameStudents << " got " << HouseName << std::endl;
}
//Prints Results
std::cout << "Number of Students in each House: \n";
std::cout << "Cornfolk:" << NumCornfolk << " Esophagus:" << NumEsophagus << " Bob:" << NumBob;
}
The line of code that reads std::cin >> NameStudents; is what's causing the problem. I've seen methods that say to use something along the lines of "std::cin.getline (name,256);" but cin.getline throws an error at the period and won't compile.
Being able to read in the names correctly is only 2/11 points, so it's not that big of a deal, but I would like to know why the suggested methods are not working here.
Thank you. This question is different from ones asked before mods.
Use std::getline, like this:
std::getline(std::cin, NameStudents);
Here's an example from https://en.cppreference.com/w/cpp/string/basic_string/getline:
std::string name;
std::cout << "What is your name? ";
std::getline(std::cin, name);
std::cout << "Hello " << name << ", nice to meet you.\n";
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 5 years ago.
Improve this question
Warning: I am brand new to programing! I am trying to create a random letter generator game for a class project. I feel like I have a decent start to it but I am having difficulty with a few points.
The program is supposed to ask the player how many games they would like to play(1-5). The maximum number of guesses they get per game is 5 and then it is supposed to print out what the correct answer was if it was not guessed. As it is, I have it so that it will run the correct number of guesses but not games and it dosent cout<< the correct answer when all guesses are done. Any help is appreciated, thanks.
#include<iostream>;
#include<cstdlib>;
#include<ctime>;
using namespace std;
int main()
{
char alphabet [27];
int number_of_games;
char guess;
int x = 1;
srand(time(0));
int n = rand() % 26 + 1;
cout<<"Weclome to the Letter Guessing game!\n";
cout<<"You have 5 chances to guess each letter.\n \n";
cout<<"How many games do you want to play?\n";
cin >> number_of_games;
cout<<"**************************************************\n\n";
while (x <= number_of_games) //Need to get it for how many rounds, not how many guesses
{
if (number_of_games < 1)
{
cout<< "Lets play game " << number_of_games << '\n';
}
//cout << (char)(n+97); //cheat to make sure working
cout<<"Enter your guess: ";
cin >> guess;
int guessValue = int(guess);
if (guessValue > (n+97))
{
cout<<"The letter you are trying to guess is before " <<guess <<"\n";
}
else if (guessValue < (n+97))
{
cout<<"The letter you are trying to guess is after " <<guess << "\n";
}
else if( (char)(n+97))
{
cout << "The answer you were looking for was " << (char)(n+97) << "\n";
}
else
{
cout<<"Your guess is correct! \n";
break;
}
//if answer is not right after x tries, cout the correct answer
x++;
}
system("pause");
return 0;
}
You can use "nested loops" - an outer loop for games, and an inner loop for turns. I've used a for loop in my example.
Also, no need to convert everything to int. char is an integral type and can be used just like a number:
while (x <= number_of_games) //Need to get it for how many rounds, not how many guesses
{
// Select a new char (a-z) for each game
char n = 97 + rand() % 27;
cout << "Lets play game " << x << '\n';
// 5 guesses
for (int number_of_guesses = 0; number_of_guesses < 5; number_of_guesses++) {
cout << "Enter your guess: ";
cin >> guess;
if (guess > n)
{
cout << "The letter you are trying to guess is before " << guess << "\n";
}
else if (guess < n)
{
cout << "The letter you are trying to guess is after " << guess << "\n";
}
else
{
cout << "Your guess is correct! \n";
// Break out of the inner for loop, not the while
break;
}
}
x++;
}
I just started learning files and I understand how to set it up and get it to work. I have to write this program where I have to allow the user to enter some information and have the user also update and adjust any data, using binary.
So I can write up until the point where the user can write to and read from the file. But I don't know how to let the user adjust data or add data.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class client {
public:
string name;
int balance;
string id;
};
int main()
{
int ans;
int x;
string nameIn;
string adjName;
client client1;
ofstream out("client1.dat", ios::binary);
cout << "\nDo you want to add information or update info" << endl;
cin >> ans;
if (ans == 1)
{
cout << "\nPlease enter the name of your client" << endl;
cin >> nameIn;
x = nameIn.length();
if (x <= 10)
{
for (int i; i < 10; i++)
{
adjName[i] = nameIn[i];
}
}
else
{
for (int i = x; i < 10; i++)
{
adjName[i] = ' ';
}
}
client1.name = adjName;
cout << "\nPlease enter the balance of your client" << endl;
cin >> client1.balance;
cout << "\nPlease enter the id of your client" << endl;
cin >> client1.id;
cout << "\nThe name of your client is " << endl << client1.name
<< endl << "\nThe balance of your client is " << endl
<< client1.balance << endl << "\nThe id of your client is "
<< endl << client1.id;
out.write(reinterpret_cast<const char*> (&client1), sizeof(client));
}
/*
else if (ans == 2)
{
string answer, newName,line;
cout << "\nWhat name do you want to update? " << endl;
cin >> answer;
cout << "\nWhat is the new name?" << endl;
cin >> newName;
if (out)
}
*/
system("pause");
return 0;
}
so the name needs to be only 10 characters long, so that we can adjust/update it. It compiles and runs, but every time the compiler gets to the part where it checks the name length, it freaks out and says "debug assertion failed"
string subscript out of range.
Also a thing about this code-- if i run it without the bits where you adjust the name to a certain array length, the program runs, and stores everything nicely. But when I try to read back the .dat, it reads it back but exits with an access violation, forcing me to manually stop the debugging. What am I doing wrong?
this is the code for reading the file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class client {
public:
string name;
int balance;
string id;
};
int main()
{
client client1;
char ans;
cout << "\nDo you want to view the information about your client?"
<< endl;
cin >> ans;
ifstream in("client1.dat", ios::binary);
if (ans == 'y' || ans == 'Y')
{
in.read(reinterpret_cast<char*> (&client1), sizeof(client));
cout << "The name is " << endl << client1.name << endl
<< "The balance is " << endl << client1.balance << endl
<< "The id is " << endl << client1.id << endl;
}
system("pause");
return 0;
}
As for the 1st part:
for (int i; i < 10; i++)
// ^
misses to initialize i to zero. Also what if the input was smaller than 10 characters? You're going to access the std::string out of bounds. You should replace the if/else and loops with simply
adjName = nameIn;
while(adjName.length() <= 10) {
adjName += ' ';
}
to get rid of the debug assertion.
For the 2nd part of the question, as already mentioned in the comments you cannot do this with a structure containing classes like std::string.
The reinterpret_cast<char*> (&client1) just obfuscates that std::string uses a pointer to the dynamically allocated character data internally, and that cannot be restored meaningfully when reading the stored data back later (hence the access violation you get).
A viable way might be to use something like
struct client {
char name[11];
int balance;
char id[5];
};
As I guess you need to do this for a homework exercise, and for this purpose that would probably be sufficient.
But you quickly can see the drawbacks, that the character data needs to be fixed in size and you cannot have arbitrary length strings. I never would use such for production ready code.
Another pitfall (as also mentioned) is, that int isn't represented in the same way (order of bytes used, i.e. endianess) in the same way for different CPU architectures. So the binary file can't be used portably with different computers.
The simplest solution is not to use a binary file, but a text formatted file and overload the std::ostream& operator<<(std::ostream&, const client&) and std::istream& operator>>(std::istream&, client&) output/input operators.
Or use some 3rd party library like boost::serialization or google protocol buffers, that supports de-/serialization to binary files.
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?