Mastermind string cout issue - c++

Ok I have been struggling with this code and I think I have it written out right but here is the rules from my teacher
1 = implies right Number, Right Place.
2 = implies right Number, Wrong Place.
0 = implies Wrong Number.
So the computer decides on 12345; the user guesses 11235; the computer should respond with 10221. Hint: Watch out for a double number like 11 when there is only one.
I have it where it does all of that except I can not get it to show a 0 when it is wrong can you please help me every single part is written except that part here is my code
// Programming 2
// Mastermind
#include "stdafx.h"
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
using namespace std;
struct fields{//the list of variables used in my program
int size = 5;;
int range = 9;
char lowest = '0';
string guess;
string answer;
int number;
int correct;
int position;
bool gameover = false;
};
void gameplay(fields & info);//declaring the function
int main()
{
fields game;
gameplay(game);//calling the function
system("pause");
return 0;
}
void gameplay(fields & info){//calling the structure into the function
srand(time(0));//to randomize number
info.answer = "";//getting the number
for (int i = 0; i < info.size; i++)
{
char ch = info.lowest + rand() % info.range;
info.answer += ch;
}
info.number = 1;
info.correct = 0;
info.position = 0;
while (!info.gameover)//using a while loop to let them go until they guess it
{
cout << "Guess #" << info.number << ": Enter 5 numbers that are '0' through '9': ";//asking them to guess
cout << info.answer;
cout << "\n";
cin >> info.guess;
if (info.guess == info.answer)//if the guess is right this will end the game
{
cout << "Right! It took you " << info.number << " move";
if (info.number != 1) cout << "s";
cout << "." << endl;
info.gameover = true;
}
int correctNumbers = 0;
for (char const &ch : info.guess) //seeing if there are numebrs in the guess that is in the answer
{
if (info.answer.find(ch) != string::npos)
{
++correctNumbers;
}
}
int const digits = 5;
int correctPositions = 0;
int correctPosition[digits];
int test = 0;
for (int i = 0; i < digits; ++i)//telling which numbers is correct and displaying the 2 or 0 for number is correct or number is wrong
{
if (info.answer[i] == info.guess[i])
{
++correctPositions;
}
if (info.answer[i] == info.guess[i]){
correctPosition[i] = 2;
cout << correctPosition[i];
}
if (correctPosition[i] != 2){
correctPosition[i] = 1;
cout << correctPosition[i];
}
if (correctPosition[i] != 2 && correctPosition[i] != 1)){
correctPosition[i] = 0;
cout << correctPosition[i];
}
}
cout << "\nYou have " << correctPositions << " numbers in the correct position " <<endl;
cout << "You have " << correctNumbers <<" correct numbers in the wrong position"<< endl;
}
cout << "GAME OVER\n\n";
}

Related

(C++) Problem with if statement ,simple == condition

I have something which outputs all the factors for an integer using a fixed loop.
in this case, int_end_int_ = 4
and middle_x_coefficient = 4
for (int i = 1; i <= int_end_int_; i++)
{
if (int_end_int_ % i == 0) // This gets the factors
{
//here
}
}
i have that inside the if loop that if i * 2 == 4, print a string. So i thought that when i = 2, it will output the string.
//inside if loop
int newi = i * 2;
//i = 2
if (newi == middle_x_coefficient) {
preroot1 = i; //ignore
cout << "prerooted";
preroot2 = i; //ignore
}
It does not output "prerooted", and i have no clue why.
Full Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "Quadratic Equation Solver ( to roots )" << endl;
cout << "Enter quadratic equation, e.x (x^2 + 4x + 4) must be in this form" << endl;
string equation;
cout << ">> ";
getline(cin, equation);
if (equation.length() < 12)
{
cout << "Please enter valid string." << endl;
while (equation.length() < 12)
{
cout << ">> ";
getline(cin, equation);
}
}
char middle_x_coefficient = equation[6]; // getting x^2 + 4(this<-)x + 4
char end_int_ = equation[11]; // getting x^2 + 4x + 4 <-- this
int preroot1 = 0;
int preroot2 = 0;
int int_end_int_ = static_cast<int>(end_int_); //convert char to int using static cast for like no reason
//nvm <- https://stackoverflow.com/questions/103512/why-use-static-castintx-instead-of-intx this says it is better bc compiler bad or smthn
int_end_int_ -= 48; //This converts the ascii value (52 for 4) to 4 (-48)
int pasti = 0;
for (int i = 1; i <= int_end_int_; i++)
{
if (int_end_int_ % i == 0)
{
cout << i << "this<- i" << endl;
cout << middle_x_coefficient << "this<- x" << endl;
int newi = i * 2;
//i = 2
if (newi == middle_x_coefficient) {
preroot1 = i;
cout << "prerooted";
preroot2 = i;
}
else if (i + pasti == middle_x_coefficient) {
preroot1 = i;
preroot2 = pasti;
}
pasti = i;
}
}
cout << preroot1 << " " << preroot2 << endl;
return 0;
}
You converted the character end_int_ to the integer int_end_int_, but you didn't convert the character middle_x_coefficient to an integer. Convert and use converted integer just as you did for end_int_.
Instead of using magic number 48, using character literal '0' is better.

Not taking the input

I want to write a program that only takes odd numbers, and if you input 0 it will output the addition and average, without taking any even number values to the average and the addition. I'm stuck with not letting it take the even values..
Heres my code so far:
int num = 0;
int addition = 0;
int numberOfInputs = 0;
cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;
for (; ;) {
cin >> num;
numberOfInputs++;
addition = addition + num;
if (num % 2 != 0) {
//my issue is with this part
cout << "ignored" << endl;
}
if (num == 0) {
cout << "Addition: " << addition << endl;
cout << "Average: " << addition / numberOfInputs << endl;
}
}
Solution of your code:
Your code doesn't working because of following reasons:
Issue 1: You adding inputs number without checking whether it's even or not
Issue 2: If would like skip even then your condition should be as follow inside of the loop:
if (num%2==0) {
cout << "ignored:" <<num << endl;
continue;
}
Solving your issues, I have update your program as following :
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num = 0;
int addition = 0;
int numberOfInputs = 0;
cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;
for (; ;) {
cin>> num;
if (num%2==0) {
cout << "ignored:" <<num << endl;
continue;
}
numberOfInputs++;
addition = addition + num;
if (num == 0) {
cout << "Addition: " << addition << endl;
cout << "Average: " << addition / numberOfInputs << endl;
break;
}
}
}
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int number;
int sum=0;
int average=0;
int inputArray[20]; // will take only 20 inputs at a time
int i,index = 0;
int size;
do{
cout<<"Enter number\n";
cin>>number;
if(number==0){
for(i=0;i<index;i++){
sum = sum + inputArray[i];
}
cout << sum;
average = sum / index;
cout << average;
} else if(number % 2 != 0){
inputArray[index++] = number;
} else
cout<<"skip";
}
while(number!=0);
return 0;
}
You can run and check this code here https://www.codechef.com/ide
by providing custom input

Printing first 100 prime numbers to a file

I have to write out a list of prime numbers from 1-100, using a function we have previously wrote, to a file. The commented out part isn't anything related; it's just the previous code we used for the function. I don't know exactly what's going on because the file isn't even being created, and the part inside the for loop is executing with just 2's, 100 times.
#include <iostream>
#include <fstream>
using namespace std;
bool isPrime(int);
int main () {
ofstream outputFile;
int p = 2;
cout << "I will be giving you the first 100 prime numbers " << endl;
cout << "And giving you a file containing those numbers." << endl;
outputFile.open("PrimeNumbers100.txt");
for (int i = 2; i <= 100; i++)
{
isPrime(p);
cout << p << endl;
outputFile << p << endl;
}
outputFile.close();
cout << "You should now have the file." << endl;
/* int n;
int counter = 0;
int p = 2;
cout << "Welcome to prime counter. " << endl;
cout << "Which prime number would you like? ";
cin >> n;
while (counter < n) {
if (isPrime(p)) {
counter++;
}
p++;
}
p = p - 1;
cout << "Prime number " << n << " is " << p << "." << endl;
*/
return 0;
}
bool isPrime(int p) {
bool result = true;
if (p < 2) {
result = false;
}
else {
int stop = (int) (sqrt(p + .5));
for (int d = 2; d <= stop; d++) {
if (p % d == 0) {
result = false;
break;
}
}
}
return result;
}
Could someone please explain what I'm doing wrong here, and why it isn't even creating the file?
You initialize p at the top with 2. You should be calling isPrime with i instead.
You're getting 2s because you're printing out and storing p, but the loop is going over i.
Here is the updated code. Upon research I did find where it was saving the files, and there are instances of it just not working at all. However, This code runs and does give me everything I need it to.. Thank you for the tips, and I appreciate the very.... constructive feedback.
#include <iostream>
#include <fstream>
using namespace std;
bool isPrime(int);
int main () {
ofstream outputFile;
cout << "I will be giving you the first 100 prime numbers " << endl;
cout << "And giving you a file containing those numbers." << endl;
outputFile.open("PrimeNumbers100.txt");
for (int i = 2; i <= 100; i++)
{
if (isPrime(i)) {
outputFile << i << endl;
}
}
outputFile.close();
cout << "You should now have the file." << endl;
return 0;
}
bool isPrime(int p) {
bool result = true;
if (p < 2) {
result = false;
}
else {
int stop = (int) (sqrt(p + .5));
for (int d = 2; d <= stop; d++) {
if (p % d == 0) {
result = false;
break;
}
}
}
return result;
}

Arrays comparison (.Txt file to user input) C++

This is a program that is suppose to compare an answer sheet (which is a .txt file) to user input. Meaning I'm comparing two arrays but I'm having a PITA time making it work. It complies just fine but it just does not compare the user input array to the .txt file array and counts everything as wrong even when I manually put in the correct answers on the user input side. Any advice or suggestions would be appreciated! PS: I cannot use vectors, only arrays. That's not a personal choice but a requirement.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int CHOICE = 20;
const char KEY = 20;
char correctAnswers[KEY];
char A, B, C, D;
char userAnswers[CHOICE];
char rightOrWrong[CHOICE];
int totalMissed;
int sum = 0;
int count = 0;
ifstream inputFile;
inputFile.open("CorrectAnswers.txt");
while (count < KEY && inputFile >> correctAnswers[count])
count++;
inputFile.close();
for (int qst = 0; qst < 20; qst++)
{
cout << "Please put an answer for the question: " << endl;
cin >> userAnswers[qst];
cout << endl;
if (userAnswers[qst] == correctAnswers[qst])
{
rightOrWrong[qst] = 'C';
}
else
{
rightOrWrong[qst] = 'I';
}
}
for (int qst = 0; qst < 20; qst++)
{
if (rightOrWrong[qst] == 'C')
{
sum += 1;
}
else
{
cout << "Answer #" << qst << " is not correct" << endl;
}
}
totalMissed = 20 - sum;
cout << "This is your final score: " << endl;
cout << "You missed " << (20 - sum) << "/20 of the questions" << endl;
cout << "You overall percentage is " << (sum / 20) << "%." << endl;
if (sum < 14 && sum >= 0)
{
cout << "You have not passed the exam. You must have a 70% or higher to pass. Study harder next time!" << endl;
}
else
{
cout << "Pat yourself on the back! You've passed the test!" << endl;
}
return 0;
}
I apologize if this looks crappily formatted, it doesn't look like this normally.

I keep getting subscript out of range don't know how to fix it [closed]

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
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
const int MAX_NUMS = 200; // Constant for the maximum number of words.
const int MAX_GUESSES = 8;
const string LETTERS = "abcdefghijklmnopqrstuvwxyz";
char inputLetter();
int findChar(char letter, string&word);
string getGuessedWord(string&secretWord, string&lettersGuessed);
string getLettersGuessed(char letter, string&lettersGuessed, int n);
void display(string&lettersGuessed, string&wordGuessed, int num, int pos);
bool isDone(string wordGuessed);
int main()
{
string oneWord; // holds one word from input file
string secretWord; // holds secret word to be guessed
string words[MAX_NUMS]; // holds list of words from input file
int randomValue; // holds index of secret word
int count = 0; // holds number of words in the file
// Declare an ifstream object named myFile and open an input file
ifstream myFile;
myFile.open("P4Words.txt");
// Exit program if cannot open file for input
if (!myFile)
{
cout << "Error: Unable to open file for input" << endl;
return 0;
}
// Input words from a file into words array
// Add your code here ...
myFile >> oneWord;
while (!myFile.eof())
{
words[count] = oneWord;
count++;
myFile >> oneWord;
}
myFile.close();
cout << count << " words loaded." << endl;
srand(static_cast<unsigned int>(time(0)));
// Select a secret word
// Add your code here ...
secretWord = words[rand() % (count + 1) ];
// Possible useful variables the loop
string lettersGuessed = ""; // holds letters guessed so far
string wordGuessed; // holds current word guessed like �_ pp_ e�
int incorrectGuesses = 0; // holds number of incorrect guesses so far
char letter; // holds a guessed letter
bool done = false; // have not guessed the word yet
int num = 8; int pos;
cout << "Welcome to the game, Hangman V1 by Your Name!" << endl;
cout << "I am thinking of a word that is " << secretWord.length()
<< " letters long." << endl;
// Set up a loop to input guesses and process
// Add your code here ...
do
{
letter = inputLetter();
pos = findChar(letter, secretWord);
wordGuessed = letter;
lettersGuessed = getLettersGuessed(letter, lettersGuessed, 8 - num);
wordGuessed = getGuessedWord(secretWord, lettersGuessed);
display(lettersGuessed, wordGuessed, num, pos);
done = isDone(wordGuessed);
num--;
} while ((num > 1) && (done == false));
// Check for won or lost
// Add your code here ...
if (done == false)
{
cout << "sorry you lose..." << endl;
}
if (done == true)
{
cout << "congratulations! " << endl;
}
system("pause"); // stop program from closing, Windows OS only
return 0;
}
// Add function definitions here ...
char inputLetter()
{
int i;
char letter;
do
{
cout << "please guess a letter: " << endl;
cin >> letter;
for (i = 0; i < 25; i++)
{
if (letter == LETTERS[i])
{
return letter;
}
}
if (letter != LETTERS[i])
{
cout << "Oops! That is an invalid character." << endl;
}
} while (letter != LETTERS[i]);
}
int findChar(char letter, string &word)
{
int i = 0; int pos = 0; bool found = false;
do
{
if (word[pos] == letter)
{
return pos;
found = true;
}
pos++;
} while (pos<word.length() - 1);
if (found == false)
{
return -1;
}
}
string getGuessedWord(string&secretWord, string&letterGuessed)
{
string temp;
temp = secretWord;
for (size_t k = 0; k <= temp.length() - 1; k++)
{
temp[k] = '_';
}
for (size_t i = 0; i <= temp.length() - 1; i++)
{
for (size_t j = 0; j <= temp.length() - 1; j++)
{
if (letterGuessed[i] == secretWord[j])
{
temp[j] = letterGuessed[i];
}
}
}
return temp;
}
string getLettersGuessed(char letter, string&lettersGuessed, int n)
{
string temp;
temp = letter;
lettersGuessed.insert(n, temp);
return lettersGuessed;
}
void display(string&lettersGuessed, string&wordGuessed, int num, int pos)
{
if (pos != -1)
{
cout << "You have " << num << " guesses left." << endl;
cout << "Letters guessed so far: " << lettersGuessed << endl;
cout << "Good guess!: " << wordGuessed << endl;
cout << "-----------------------------------------------------" << endl;
}
if (pos == -1)
{
cout << "You have " << num << " guesses left." << endl;
cout << "Letters guessed so far: " << lettersGuessed << endl;
cout << "Oops! that letter is not my word: " << wordGuessed << endl;
cout << "-----------------------------------------------------" << endl;
}
}
bool isDone(string wordGuessed)
{
bool done = false; int k = 0;
for (size_t i = 0; i <= wordGuessed.length() - 1; i++)
{
if (wordGuessed[i] == '_')
{
k++;
}
}
if (k == 0)
{
done = true;
}
return done;
}
it says subscript is out of range I need help to fix it
let me know how to fix it please its a project that is due very soon
that's all I got so far
Change:
for (size_t i = 0; i <= temp.length() - 1; i++)
to:
for (size_t i = 0; i <= letterGuessed.length() - 1; i++)