Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a hangman program, but I'm having issues with randomly choosing a word out of the list...
I get the errors:
-error C2661: 'rand' : no overloaded function takes 1 arguments
-IntelliSense: too many arguments in function call
They are both referring to the rand function noted in the code where I'm trying to randomly choose a word out of the array so the user can guess.
// Hang.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
using namespace std;
const int MAXLENGTH=80;
const int MAX_TRIES=5;
const int MAXROW=7;
int letterFill (char, char[], char[]);
void initUnknown (char[], char[]);
int main ()
{
char unknown [MAXLENGTH];
char letter;
int num_of_wrong_guesses=0;
char word[MAXLENGTH];
char words[][MAXLENGTH] =
{
"india",
"america",
"germany",
"china",
"canada"
};
//THIS IS WHERE THE ISSUE IS OCCURRING vvvvvvv
//choose and copy a word from array of words randomly
rand();
int n=rand(5);
strcpy(word,words[n]);
// Initialize the secret word with the * character.
initUnknown(word, unknown);
// welcome the user
cout << "\n\nWelcome to Hangman!";
cout << "\n\nYou have " << MAX_TRIES << " tries to try and guess the word.";
cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
// Loop until the guesses are used up
while (num_of_wrong_guesses < MAX_TRIES)
{
cout << "\n\n" << unknown;
cout << "\n\nGuess a letter: ";
cin >> letter;
// Fill secret word with letter if the guess is correct,
// otherwise increment the number of wrong guesses.
if (letterFill(letter, word, unknown)==0)
{
cout << endl << "Sorry, that letter was wrong." << endl;
num_of_wrong_guesses++;
}
else
{
cout << endl << "You found a letter!" << endl;
}
// Tell user how many guesses has left.
cout << "You have " << MAX_TRIES - num_of_wrong_guesses;
cout << " guesses left." << endl;
// Check if they guessed the word.
if (strcmp(word, unknown) == 0)
{
cout << word << endl;
cout << "You guessed it!";
break;
}
}
if(num_of_wrong_guesses == MAX_TRIES)
{
cout << "\nSorry, you lose...you've been hanged." << endl;
cout << "The word was : " << word << endl;
}
getch();
return 0;
}
/* Take a one character guess and the secret word, and fill in the
unfinished guessword. Returns number of characters matched.
Also, returns zero if the character is already guessed. */
int letterFill (char guess, char secretword[], char guessword[])
{
int i;
int matches=0;
for (i = 0; secretword[i]!='\0'; i++)
{
// Did we already match this letter in a previous guess?
if (guess == guessword[i])
return 0;
// Is the guess in the secret word?
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
// Initialize the unknown word
void initUnknown (char word[], char unknown[])
{
int i;
int length = strlen(word);
for (i = 0; i < length; i++)
unknown[i]='*';
unknown[i]='\0';
}
// end
rand takes no argument
You probably want :
int n=rand() % 5;
std::rand() generates a pseudo random number, if you want a number 0, 1, 2 3 or 4, which i guess you are trying to do use the following:
int n = rand()%5;
This generates a random number and then the % gives the rest value if you would divide by 5. If the random number is 12, you can 'put two fives in it', and the rest value will be 2.
One thing to note is that in C++ using rand() is generally a bad idea, because it will not give you a truly random number, and using % makes it worse, but I think you will be fine since this is just a small program.
Watch this talk if you want to know how to properly generate a random number in c++
Related
I am writing a code that generates a random number then assign the number to a letter in string letters then user has to guess the letter.
I am trying to loop the the question "Enter one lowercase letter: " if the user enters a letter that does not match randomLetter, but at the same time I have to make sure the letter is all in lower case (something we haven't learned in class but after searching I found a solution, hopefully it's the right way to go about it).
This while loop ends if user enters the incorrect lower letter. It does work when the letterGuess matches randomLetter.
The other thing I have to do is if user enters an incorrect lower letter then it needs to give feedback that the correct letter comes before or after the entered letter.
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include <algorithm>
using namespace std;
//function prototype
void displayNumber(int);
int main()
{
string letters = "abcdefghijklmnopqrstuvwxyz";
string randomLetter;
string letterGuess = "";
string wordLocation = " ";
int randomNumber = 0;
//display random number then assign a random number to letter string
displayNumber(randomNumber);
randomLetter = letters[randomNumber];
while (letterGuess.length() != 1) {
//ask user to enter a lowercase letter and determine if it matches the random letter
cout << "Enter one lowercase letter: ";
getline(cin, letterGuess);
if (all_of(letterGuess.begin(), letterGuess.end(), &::isupper)) {
cout << "letter must be lowercase.";
}
else if (randomLetter.find(letterGuess, 0) == -1) {
cout << "\nYou guessed the correct letter.";
}
else {
wordLocation.insert(0, letters);
} //end if
} //end while
return 0;
} //end of main function
void displayNumber(int num)
{
srand(time(0));
num = (rand() % 26) + 1;
cout << num << endl
<< endl;
} // end of displayNumber function
The specific problems you highlighted is caused by the looping condition,
while(letterGuess.length() != 1)
here when the user in the first iteration enters just one letter, the letterGuess string will have size = 1, and hence will cause breaking of loop.
Another problem is the fact that randomNumber remains 0, for it not to remain zero the displayNumber function must take a reference or return a value.
EDIT
To update randomNumber, modify the display function to :
int displayNumber()
{
srand(time(0));
int num = (rand() % 26) + 1;
cout << num << endl
<< endl;
return num;
}
and in the main:
randomNumber = displayNumber();
or alternatively
void displayNumber(int& num)
{
srand(time(0));
num = (rand() % 26) + 1;
cout << num << endl
<< endl;
}
and in the main:
displayNumber(randomNumber);
maybe rename it to generateRandom() which seems more accurate?
You your problem might be is here:
while (letterGuess.length() != 1)
because you when you enter one character you break the loop. To fix this you might go different routes, but easiest one is to check if letter is lower or upper.
while (letterGuess.length() != 1 || std::islower(letterGuess[0]))
Also now that I look at it closer, did you want to check if any characters in string are upper or all of them are upper?
all_of(letterGuess.begin(), letterGuess.end(), &::isupper)
would check if all characters are lower, but to check if only one character is upper use any_of()
any_of(letterGuess.begin(), letterGuess.end(), &::isupper)
Here is my little example code:
#include <iostream>
#include <algorithm>
using namespace std;
int main (void) {
std::string s = "Hello";
if (any_of(s.begin(), s.end(), &::isupper))
std::cout << "One is upper\n\n";
if (all_of(s.begin(), s.end(), &::isupper))
std::cout << "All are upper\n";
else
std::cout << "some might be upper\n";
return 0;
}
Output
EXECUTING ==================================================
One is upper
some might be upper
DONE ==================================================
Since you are newbie, another thing that I just noticed that I still remember from my newbie days. call srand(time(0)); once. Maybe at the begging of main(). Way you have it does produces the same random number every time. Read this
The program won't compile in Visual Studio Community, I have no idea why. I've looked into the function and can't seem to find an answer. Any help would be appreciated as this is for my module at university. I'm a little new to C++ but have some experience in other languages. I just can't seem to find how to get the program to run. I get the below error codes when compiling:
main.cpp: In function ‘void runGame(std::__cxx11::string*, std::__cxx11::string*, int)’:
main.cpp:115:53: error: cannot convert ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’
to ‘std::__cxx11::string* {aka std::__cxx11::basic_string<char>*}’
for argument ‘1’ to ‘std::__cxx11::string answersGiven(std::__cxx11::string*, std::__cxx11::string*, int, int)’
answersGiven(correctAns[0], wrongAns[0], max, max2);
Here is the Code:
#include<iostream>
#include<string>
using namespace std;
int inputCheck(string menu, int limit); // Validates User Input for topic and difficulty selection.
void runGame(string questions[], string answers[], int level); // Function runs game based on questions.
string modifyQuestion(string q, int mod); // Function modifies question based on difficulty level.
string answersGiven(string correct[], string wrong[], int maxC, int maxW);
int main() {
string questions[3][4] = { // 2D array storing answers. Each row stores a Country.
{ "England", "Wales", "France", "Germany" }, // Stores Europe Questions.
{ "Brazil", "Peru", "Argentina", "Columbia" }, // Stores Additional Questions.
{ "Q1", "Q2", "Q3", "Q4" } // Stores South American Questions.
};
string answers[3][4] = { // 2D array storing answers. Each row stores a city.
{"London", "Cardiff", "Paris", "Berlin"}, // Europe Answers.
{"Brasila", "Lima", "Buenos Aires", "Bogota"}, // South America Answers.
{ "A1", "A2", "A3", "A4" } // Stores additional answers.
};
string topics[3] = { "Capital Cities", "" };
char replay; // Variable to check if the user wants to continue playing.
do {
cout << "Please choose one topic for the quiz:\n";
int choice = inputCheck("1: Europe\n2: South America\n3: Testing", 3); // Gets topic choice via validation function.
cout << "\nNow Select a Difficulty:\n";
int difficulty = inputCheck("1: Easy\n2: Medium\n3: Hard", 3); // Gets difficulty choice via validation function.
choice--;
// run the game
runGame(questions[choice], answers[choice], difficulty);
// Checks if user wants to replay game.
cout << "Do you want to play again? Press (Y) to replay: ";
cin >> replay; // Grabs input from user.
replay = toupper(replay); // Sets data to upper case.
} while (replay == 'Y');
return 0;
}
int inputCheck(string menu, int limit) {
cout << menu << endl; // Presents menu of options.
int num; // Variable to store user's input.
cin >> num; // gets user's input.
while (cin.fail() || num < 1 || num > limit) {
cout << "Invalid Input..." << endl; // Outputs error message.
cout << menu << endl; // Presents menu again.
cin.clear(); // Clearsinput error glag.
cin.ignore(1000, '\n'); // Ignores previous inputted data.
cin >> num; // grabs input again.
}
return num;
}
void runGame(string questions[], string answers[], int level) {
string correctAns[] = {};
string wrongAns[] = {};
cin.ignore(1000, '\n'); // Ignore any trailing enter keys in input stream.
int lives = 3; // Stores the amount of users lives.
string answer; // Stores user's answer.
int count = 0; // Keeps track of the current question.
int score = 0; // Keeps track of user's score.
while (lives > 0 && count < 4) {
string question = questions[count]; // Gets current question from array.
// Modifying question if medium or hard difficulty selected.
if (level == 2) {
// Medium
question = modifyQuestion(question, 6);
}
else if (level == 3) {
// Hard
question = modifyQuestion(question, 2);
}
// Asking Question.
cout << "What is the capital city of " << question << endl; // Asks user the question.
getline(cin, answer); // Gets answer from user, includes answers that are more than one word.
answer[0] = toupper(answer[0]); // Converts first character to upper case.
int max = 0;
int max2 = 0;
if (answer == answers[count]) { // Checks user's answer against current answer.
cout << "Well Done! You've got one right" << endl; // Correct answer message.
count++; // Adds one to question counter.
score++; // Adds one to score.
correctAns[count] = answer;
max++;
}
else {
lives--; // Deducts one from lives.
cout << "Oops, Not quite right... You have " << lives << " lives remaining."; // Outputs incorrect message.
wrongAns[count] = answer;
max2++;
}
answersGiven(correctAns[0], wrongAns[0], max, max2);
}
if (lives == 0 && score == 0) { // Checks if user didnt get anything correct.
cout << "Wow.. 0 / 4. Thats not good." << endl;
}
else {
cout << "You got " << score << " Correct and had " << lives << " lives remaining" << endl;
}
cout << "\nThese are the questions you got wrong:\n";
}
string modifyQuestion(string q, int mod) {
for (int i = 0; i < q.length(); i++) {
if (i % mod == 0) { // If counter is divisible by the mod value.
q[i] = '*'; // Change current letter to an aterix.
}
}
return q; // return modified string back to the function.
}
string answersGiven(string correct[], string wrong[], int maxC, int maxW) {
for (int i = 0; i < maxC; i++) {
cout << correct[i] << " - Correct" << endl;
}
for (int i = 0; i < maxW; i++) {
cout << wrong[i] << " - Incorrect" << endl;
}
}
error message.png
These are the errors
1."message": "cannot open source file \"iostream\"",
2.#include errors detected. Please update your includePath. Squiggles are disabled for this
translation unit (C:\Users\USER\first.cpp).
3.cannot open source file "cstdlib"
4.cannot open source file "ctime"
5.cannot open source file "string"
AND
This is my code
#include <iostream>
#include <cstdlib>
#include<ctime>
#include <string>
using namespace std;
const int MAX_TRIES=5;
int letterFill (char, string, string&);
int main ()
{
string name;
char letter;
int num_of_wrong_guesses=0;
string word;
string words[] =
{
"india",
"pakistan",
"nepal",
"malaysia",
"philippines",
"australia",
"iran",
"ethiopia",
"oman",
"indonesia"
};
//choose and copy a word from array of words randomly
srand(time(NULL));
int n=rand()% 10;
word=words[n];
// Initialize the secret word with the * character.
string unknown(word.length(),'*');
// welcome the user
cout << "\n\nWelcome to hangman...Guess a country Name";
cout << "\n\nEach letter is represented by a star.";
cout << "\n\nYou have to type only one letter in one try";
cout << "\n\nYou have " << MAX_TRIES << " tries to try and guess the word.";
cout << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
// Loop until the guesses are used up
while (num_of_wrong_guesses < MAX_TRIES)
{
cout << "\n\n" << unknown;
cout << "\n\nGuess a letter: ";
cin >> letter;
// Fill secret word with letter if the guess is correct,
// otherwise increment the number of wrong guesses.
if (letterFill(letter, word, unknown)==0)
{
cout << endl << "Whoops! That letter isn't in there!" << endl;
num_of_wrong_guesses++;
}
else
{
cout << endl << "You found a letter! Isn't that exciting!" << endl;
}
// Tell user how many guesses has left.
cout << "You have " << MAX_TRIES - num_of_wrong_guesses;
cout << " guesses left." << endl;
// Check if user guessed the word.
if (word==unknown)
{
cout << word << endl;
cout << "Yeah! You got it!";
break;
}
}
if(num_of_wrong_guesses == MAX_TRIES)
{
cout << "\nSorry, you lose...you've been hanged." << endl;
cout << "The word was : " << word << endl;
}
cin.ignore();
cin.get();
return 0;
}
/* Take a one character guess and the secret word, and fill in the
unfinished guessword. Returns number of characters matched.
Also, returns zero if the character is already guessed. */
int letterFill (char guess, string secretword, string &guessword)
{
int i;
int matches=0;
int len=secretword.length();
for (i = 0; i< len; i++)
{
// Did we already match this letter in a previous guess?
if (guess == guessword[i])
return 0;
// Is the guess in the secret word?
if (guess == secretword[i])
{
guessword[i] = guess;
matches++;
}
}
return matches;
}
Your compiler cannot find the header files that you're including, though since you're just including headers from the standard library, there's most likely something wrong with your installation, or your environment. It could be that you're just confusing a C compiler with a C++ compiler (such as clang and clang++), or perhaps you're using a compiler that doesn't actually ship with a standard library, as is also the case with clang on Windows, which uses MSVC's standard library.
You can figure that out by trying to include a header from the C standard library, such as "stdlib.h", and see if the compiler can find it. If it can, then you're just using the wrong compiler, and if it can't, then you either lack a standard library, or your environment isn't set up properly and your compiler can't find it, but without knowing what compiler you're using, and how you're invoking it, I can't really give a detailed answer.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
#include <iostream>
using namespace std;
int countLetters(char text[], char letter);
int main()
{
char letter;
cout << "Enter a letter: ";
cin >> letter;
cin.ignore();
char text[1024];
cout << "Enter text: ";
cin.getline(text, 1024);
int letterCount = countLetters(text, letter);
cout << "Number of '" << letter << "'s: " << letterCount << endl;
return 0;
}
int countLetters(char text[], char letter)
{
int letterCount = 0;
for (int i = 0; i <= text[i]; i++)
{
if (letter == text[i])
letterCount++;
}
return letterCount;
}
This code, as written, is designed to ask the user for, first, the letter they want to search for in a line of text. Second, it will ask the user to input the line of text they want to have searched. Finally, it will spit out how many letters there are in the specific line of text they input.
My specific error lies here: when user asks for 'e' in "CS 124 - Introduction to Software Development", program only declares that there is one 'e' . I'm unsure what's wrong, because when you run the program and input 'o' while asking to search the exact same line of text, you get the proper number of 'o' values returned, 4.
Any ideas as to what my error is and why it glitches when searching for 'e' ?
Your for condition is wrong, the for loop should continue while i is less than text's length not the value of text[i]. Since this is C++ you should use strings not character arrays, why make it harder on yourself?
The code below is a C++ approach, note that my C++ is a bit rusty and the code might contain errors.
#include <iostream>
#include <string>
using namespace std;
int countLetters(string text, char letter);
int main() {
char letter = ' ';
string text;
cout << "Enter a letter: ";
cin >> letter;
cin.ignore();
cout << "Enter text: ";
getline(cin, text); // use 'getline(cin, text)' instead of 'cin >> text'
int letterCount = countLetters(text, letter);
cout << "Number of '" << letter << "'s: " << letterCount << endl;
return 0;
}
int countLetters(string text, char letter) {
int letterCount = 0;
for (int i = 0; i < text.size(); i++) {
if (letter == text[i]) {
letterCount += 1;
}
}
return letterCount;
}
change the condction
i <= text[i]
to
text[i] != '\0'
#include <iostream>
#include <string.h>
#include <string>
#include <fstream>
using namespace std;
int get_ascii_int(char ch);
int get_offset_ascii(char ch2, int offset);
//int print_string_ints(string test_string);
int method3_substitution_abc();
//above are the function declarations
int main()
{
string test_string;//input of string
char ch = 0;//used in method1
char ch2 = 0;//used in method2
int index1 = 0;//used in for loop method1
int index2 = 0;//used in for loop method2
int offset = 0;//input of how much to offset
int new_ascii = 0;//the new ascii with offset
int ascii_value1 = 0;//the ascii value of the char
int option;//the menu choice of encryption method
int decision;//the decision to save or display
ofstream method1;//method 1 text file
ofstream method2;//method 2 text file
ofstream method3;//method 3 text file
string test_string_copy;//copy of string method 2
//Below is a description of the methods of encryption
cout << "There are three methods of encryption, listed below, to choose from: " << endl;
cout << "1. Converting characters into the corresponding ASCII values. " << endl;
cout << "2. Shifting characters right/left using the ASCII value of the characters ";
cout << "and a set offset amount. " << endl;
cout << "3. Using a reverse alphabet, so each letter will be replaced with the letter ";
cout << "on the opposite end of the alphabet. For example, A would become Z. " << endl;
cout << "Which encryption method would you like to use, 1, 2, 3? ";
cin >> option;
switch (option)
{
case '1':
method1.open("method1.txt");
cout << "Input a word or name: ";
getline(cin, test_string);
for (; index1 < test_string.size(); index1++);
{
ascii_value1 = get_ascii_int(test_string[index1]);
}
cout << "Would you like to display the file or save it, enter 1 for display or 2 for save?";
cin >> decision;
if (decision == '1')
{
cout << "The encrypted code is " << ascii_value1 << endl;
}
else
{
if (method1.is_open())
{
method1 << "The encrpyted code is " << ascii_value1 << endl;
method1.close();
}
else
cout << "Unable to open file." << endl;
}
break;
case '2':
method2.open("method2.txt");
cout << "Input a word or name: ";
getline(cin, test_string);
test_string_copy = test_string;
for (; index2 < test_string_copy.size(); index2++);
{
new_ascii = get_offset_ascii(test_string_copy[index2], ch2);
}
cout << "Would you like to display the file or save it, enter 1 for display or 2 for save?";
cin >> decision;
if (decision == '1')
{
cout << "The encrypted code is " << new_ascii << endl;
}
else
{
if (method2.is_open())
{
method2 << "The encrypted code is " << new_ascii << endl;
method2.close();
}
else
cout << "Unable to open file." << endl;
}
break;
case '3':
method3.open("method3.txt");
method3_substitution_abc();
break;
}
return 0;
}
//listed below are the function definitions
int get_ascii_int(char ch)
{
return ((int)ch);
}
int get_offset_ascii(char ch2, int offset)
{
int new_offset_value;//the value after adding the determined offset to the ascii value of the letter
new_offset_value = (int)ch2 + offset;
(char)new_offset_value;
return (new_offset_value);
}
//int print_string_ints(string test_string)
//{
//for (int i = 0; i < test_string.size(); i++)
//{
//(int)test_string[i++];
//}
//return 0;
//}
int method3_substitution_abc()
{
char test_string[100];
cout << "Enter a name or phrase: ";
cin >> test_string;
if (isupper((int)test_string))
{
int stalpha = 65;//start of alphabet
int endalpha = 90;//end of alphabet
char b[100];//array to reverse the alphabet
for (int i = 0; test_string[i] != '\0'; i++)
{
b[i] = endalpha - (test_string[i] - 65);
}
}
else if (islower((int)test_string))
int stalpha = 97;//start of alphabet
int endalpha = 122;//end of alphabet
char b[100];//array to reverse the alphabet
for (int i = 0; test_string[i] != '\0'; i++)
{
b[i] = endalpha - (test_string[i] - 97);
}
return 0;
}
I am trying to write this encryption program. And I am just getting really confused on why it won't run.
For example the switch statement is not running correctly, it will go to the correct case and then skip the input of the string?
This is my first experience with C++ so I struggle to debug.
I am having issues with saving the file to a text file after the user chooses to save or display? It has to be done after every case in the switch statement.
I also know the for loops I am using are not correct for method 1 and 2? Could someone check those out and tell me what the issue is. I am pretty sure it has to do with the parameters for the for loop.
And I don't know if I should use a string or an array for this? (In the part where the user inputs a string
At least the first problem you've identified (with the switch statement) is pretty simple and clear.
You've defined option as an int, so when you read it it's read as an integer. That means if the user enters 1, it'll have the value 1, which is different from the value '1'. '1' is a character that will (for example) print as 1, but its value is actually 49 in most character sets.
You have two obvious choices: either change option to be a char, so it'll be read as a character instead of an integer, or else change the values in the switch statement from '1', '2', etc., to just 1, 2, etc.
At a guess, the problem you're seeing from getline is a fairly common one when you mix a string extractor (e.g., cin >> my_string;) with std::getline. The string extractor extracts a string from the stream, but leaves the new-line character in the stream buffer. Then when you call std::getline, it reads that new-line as an empty string, so it doesn't wait for you to enter more input.
If you really have to mix the two this way, you probably want to add a call to std::cin.ignore to read and ignore any data up to and including the new-line character. Then when you call std::getline, it'll actually read some data.