I've been making a little memory game as an exercise from a textbook I'm doing. It's called Grandma's trunk and it works by in one turn you found an item in the trunk and the next turn you say you found the previous item and the newest item on this turn...I think.
Mostly it's an exercise on using functions, which I think I've gotten down pretty well. But my output is completely wrong. I've believe I've located the problem in one function where I'm supposed to analyze the first character and decided if it needs an AN or A or THE before the string. There might be a problem with the random function I'm using to throw in predefined items from a small database. The int main() function is supposed to be relatively complete, this is just an exercise to master functions...which I, sorta? Would rather call it novice experience.
I thought that perhaps I was running into the getline bug where it couts a blank line, and from my understanding, is fixed by cin.ignore(); but all that did was force me to press enter twice when I enter data. Which...I sort of like. Perhaps I'm using gizmos like isupper and .at() wrong? I tried using find_first_of but it didn't really change anything.
output calling the storage trunk and the owner grandma and just using word1 word2 word3... wordn....as items found leaves me with the output.
In grandma trunk you've found a
and an ord3 word1.
it completely muddles up the output. I'm starting to think that the int main() body I was given wasn't exactly stellar. But I can't be 100% confident in my article function. Any help would just be incredible. I've been struggling using this among many books and advice from a buddy to teach myself a little about programming. It's been a rather huge headache.
program itself
#include <iostream>
#include <string>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
using namespace std;
string CorrectArticle(string phrase);
string GetPhrase(void);
bool Continue(void);
string UpperCase(string);
string RandomItem(void);
const string PUNCTUATION = ".";
int main(){
//Variables
int turn;
bool flag;
string phrase,
article,
story, item,
storage, owner;
srand(time(NULL));
cout << "Welcome to Grandmother's Trunk 9000" << endl;
cout << "This is a memory game. Each turn a player" << endl;
cout << "Says an item to place inside a trunk. " << endl;
cout << "And the next player has to say what the " << endl;
cout << "previous player said plus his/her own item." << endl;
cout << "This will go around in revolving turns." << endl;
cout << endl << endl;
cout << "But Grandma's Trunk is a little dry..." << endl;
cout << "Let's change what the storage is and " << endl;
cout << "Who owns it." << endl << endl;
//define storage variable
cout << "What exactly is this storage?" << endl;
getline (cin, storage);
cout << "So the items are stored in " << storage << endl;
cout << endl;
//define owner
cout << "Who owns this " << storage << " ?" << endl;
getline (cin, owner);
cout << "The owner is " << owner << endl;
story = "In "+ owner + " " + storage + " you've found ";
turn = 0;
flag = Continue();
//While flag is true
while (flag) {
if (turn %2 == 0) {
item = GetPhrase();
} else {
item = RandomItem();
}
//set corrected item to article
article = CorrectArticle(item);
//advance the story every item
story = story + "\n and " + article + " " + item;
cout << story << PUNCTUATION << endl;
turn++;
flag = Continue();
}
return (0);
}
//Gives A, AN, and THE to correct words
// An if phrase starts with i,e,i,o,u or y
// A if phrase starts with other lower case letters
// The for phrases that start with an uppercase letter
string CorrectArticle(string phrase){
int i=0;
string correctedString;
string stringAn;
string stringA;
string stringThe;
stringAn= " an ";
stringA = " a ";
stringThe= "The ";
if (GetPhrase().at(i) = "a" or "e" or "i" or "u"){
correctedString = stringAn + GetPhrase();
}else if (isupper(GetPhrase().at(i))){
correctedString = stringThe + GetPhrase();
}else{
correctedString = stringA + GetPhrase();
}
return correctedString;
}
//This function takes no parameters
//and returns the user's input
string GetPhrase(void){
string itemInput;
cout << "\nWhat did you find? \n" << endl;
getline (cin, itemInput);
cout << "\nYou found " << itemInput << endl;
cin.ignore();
return itemInput;
}
//Asks user if they wish to continue
bool Continue(void){
//return false if no, true if yes
string continueString;
cout << "Would you like to continue?";
cout << " Yes or No would suffice" << endl;
getline(cin,continueString);
UpperCase(continueString);
cout << "You picked " << continueString;
if (UpperCase(continueString).find("NO") != string::npos){
return false;
} else if (UpperCase(continueString).find("YES") != string::npos){
return true;
}
}
//Changes the string to uppercase
string UpperCase(string stringUpper){
int i = 0;
while (i<stringUpper.size()){
stringUpper[i] = toupper(stringUpper[i]);
i++;
}
return stringUpper;
}
//Randomizes items found in game
string RandomItem(void){
int randomNumber;
int maxNumberOfItems = 5;
string randomizedItem;
randomNumber= rand() % maxNumberOfItems;
switch (randomNumber){
case 0:
randomizedItem = "Smaug";
break;
case 1:
randomizedItem = "Batman";
break;
case 2:
randomizedItem = "Yoda";
break;
case 3:
randomizedItem = "Paul Atreides";
break;
case 4:
randomizedItem = "Captain Kirk";
break;
default:
cout << "ERRORRRR! PANIC!" << endl;
}
return randomizedItem;
}
Remember that = is assignment, == for compare.
Also remember that you have to compare variable with value, such as:
if ((string == "a") or (string == "e") ...
If the or works for you, all the best. I've only been able to use ||. Must be compiler conformity issues.
Try this:
bool is_vowel(char letter)
{
const std::string vowels("aeiouAEIOU");
return (vowels.find_first(letter) != std::string::npos);
}
In other words, I place all the vowels in a string a search the string. If there is a match, the letter is a vowel.
Related
I'm trying to make a small library system where the user can add new book details(name, author & price). When implementing the FileIO system to read from a file the details of every book using the getline functions it becomes harder to separate my variables when I try to store them in temporary variables.
Ex:
"No Is a four letter word,Chris Jericho,17.67,"
"Harry Potter,JK Rowling,23.98,"
PS:Is there a better solution than adding the comma?
I tried to add a ',' character to separate every my strings but I need a better and more efficient solution that works with the getLine function.
int main(){
vector<Book> library;
//----Loading File Data_START
string line;
int nbArg=0;
string tempName, tempAuthor, tempPrice;
ifstream myfileL("List.txt");
if (myfileL.is_open())
{
while (getline(myfileL, line))
{
tempPrice=tempAuthor = tempName = "";
for (int j = 0; j < line.size(); j++){
if (line.at(j) == ','){
nbArg++;
}
else{
switch (nbArg){
case 0:
tempName += (line.at(j));
break;
case 1:
tempPrice += (line.at(j));
break;
case 2:
tempAuthor += (line.at(j));
break;
}
}
}
cout << tempName << endl << tempAuthor << endl << tempPrice << endl;
cout << "End of Line"<< endl;
nbArg = 0;
}
cout << "---------------------------" << endl;
myfileL.close();
}
else cout << "Unable to open file";
//----Loading File Data_END
char inputKey = 's';
cout << "-----------------WELCOME----------------" << endl;
while (inputKey != 'q')
{
cout << "---------------------------------------" << endl;
cout << "Click \"1\" to add a book to your library" << endl;
cout << "Click \"2\" to show how the number of books your possess" << endl;
cout << "Click \"3\" to show details about your books" << endl;
cout << "Click \"q\" to quit" << endl;
cin >> inputKey;
switch (inputKey)
{
case '1':
addElem(library);
break;
case '2':
cout << "You now own " << libSize(library) << " books !" << endl;
break;
case '3':
showDetails(library);
break;
case 'q':
cout << "GOODBYE!" << endl;
Sleep(2000);
break;
}
}
return 0;
}
Use specialized file format, which can contain structure (for example json, xml). This will prevent many, many problems.
If you can't, then add a separator character (just like you did), but pick one, that has least chances to occur in real strings. So for example end of line (every variable would go on it's own line) or \0 or \t.
Here is a solution on a smooth way to load the library. You can let the BookList.txt file be delimited by TABs \t between Name, Author and Price instead of a comma , and then use getline() to separate with a TAB as in my example below.
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <vector>
using namespace std;
const char TAB = '\t';
struct StructBook {
string Name, Author;
double Price;
};
vector<StructBook> Library;
void GetBookDetails(string LineBookDetails, StructBook & Book) {
string string_Price;
stringstream StringStreamBookDetails(LineBookDetails);
getline(StringStreamBookDetails, Book.Name, TAB);
getline(StringStreamBookDetails, Book.Author, TAB);
getline(StringStreamBookDetails, string_Price, TAB);
stringstream(string_Price) >> Book.Price;
}
bool LoadLibrary() {
ifstream FileBookList("BookList.txt");
if(FileBookList.is_open()) {
string LineBookDetails;
StructBook Book;
while(getline(FileBookList, LineBookDetails)) {
GetBookDetails(LineBookDetails, Book);
Library.push_back(Book);
cout << Book.Name << ", " << Book.Author << ", " << Book.Price << endl;
}
FileBookList.close();
return true;
} else {
return false;
}
}
int main(){
if(!LoadLibrary())
cout << "Error: Unable to load library";
//Rest of your program goes here
return 0;
}
Your BookList.txt should look like this:
No Is a four letter word Chris Jericho 17.67
Harry Potter JK Rowling 23.98
This is for an intro c++ class, the prompt reads:
Print the number of words that begin with a certain character. Let the user enter that character.
Although, I'm not sure how to do this.
Do I use parsing strings? I tried this because they inspect string data type but I kept getting errors so I took it out and changed it to characters. I want to learn how to do the "total_num" (total number of words that start with the letter the user chooses) and I also need some help with my for loop.
Example of desired output
user types in: a
outputs: "Found 1270 words that begin with a"
user types in: E
outputs: "Found 16 words that begin with E"
user types in: #
outputs: "Found 0 words that begin with #"
(I think I got this part down for non-alphabetical)
The data is from a file called dict.txt, it's a list of many words.
Here's a small sample of what it contains:
D
d
D.A.
dab
dabble
dachshund
dad
daddy
daffodil
dagger
daily
daintily
dainty
dairy
dairy cattle
dairy farm
daisy
dally
Dalmatian
dam
damage
damages
damaging
dame
My program:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
const int NUM_WORD = 21880;//amount of words in file
struct dictionary { string word; };
void load_file(dictionary blank_array[])
{
ifstream data_store;
data_store.open("dict.txt");
if (!data_store)
{
cout << "could not open file" << endl;
exit(0);
}
}
int main()
{
dictionary file_array[NUM_WORD];
char user_input;
int total_num = 0;
load_file(file_array);
cout << "Enter a character" << endl;
cin >> user_input;
if (!isalpha(user_input))
{
cout << "Found 0 that begin with " << user_input << endl;
return 0;
}
for (int counter = 0; counter< NUM_WORD; counter++)
{
if (toupper(user_input) == toupper(file_array[counter].word[0]));
//toupper is used to make a case insensitive search
{
cout << "Found " << total_num << " that begin with " << user_input << endl;
//total_num needs to be the total number of words that start with that letter
}
}
}
There are a few things you can do to make your life simpler e.g. using a vector as the comment suggested.
Let's look at your for loop. There are some obvious syntax problems.
int main()
{
dictionary file_array[NUM_WORD];
char user_input;
int total_num = 0;
load_file(file_array);
cout << "Enter a character" << endl;
cin>>user_input;
if(!isalpha(user_input))
{
cout << "Found 0 that begin with " << user_input << endl;
return 0;
}
for(int counter = 0;counter< NUM_WORD; counter++)
{
if (toupper(user_input) == toupper(file_array[counter].word[0]));
// ^no semi-colon here!
//toupper is used to make a case insensitive search
{
cout<< "Found " << total_num << " that begin with "<<
user_input << endl;
//total_num needs to be the total number of words that start with that letter
}
}//<<< needed to end the for loop
}
Let's get the for loop right. You want to count the matches in a loop and then report when you have finished the loop.
int total_num = 0;
//get character and file
for(int counter = 0;counter< NUM_WORD; counter++)
{
if (toupper(user_input) == toupper(file_array[counter].word[0]))
^^^no semi-colon here!
{
++total_num;
}
}
cout<< "Found " << total_num << " that begin with "<< user_input << endl;
I've got these 2 programs for the current chapter in my C++ class that I cant seem to get to work and I dont understand why.
The first project requests
"Create a program that displays the appropriate shipping charge based on the zip code entered by the user. To be valid, the zip code must contain exactly five digits and the first three digits must be either “605” or “606”. The shipping charge for “605” zip codes is $25. The shipping charge for “606” zip codes is $30. Display an appropriate error message if the zip code entered is invalid. Use the sentinel value “X” to end the program."
#include <iostream>
#include <string>
using namespace std;
string zipCode = "";
string zip = "";
int main() {
cout << "ENTER AN X TO STOP ZIP CODE DATA ENTRY." << endl << endl;
cout << "Enter Zip Code: ";
getline(cin, zipCode);
while (zipCode != "x")
{
if (zipCode.length() == 5)
{
if (zipCode.find("605", 0))
{
cout << "Shipping charge is $25" << endl;
}
else if (zipCode.find("606", 0))
{
cout << "Shipping charge is $30" << endl;
}
else
cout << "Invalid Zip Code.";
}
else
{
cout << "Zip code must contain exactly 5 digits." << endl;
}
cout << "Enter Zip Code: ";
getline(cin, zipCode);
}
cout << endl << "End of Program.";
return 0;
}
I tried a similar structure for the second program and cant get it to work properly either.
Create a program that displays the color of the item whose number is entered by the user. All item numbers contain exactly seven characters. All items are available in four colors: blue, green, red, and white. The fourth character in the item number indicates the item number, as follows: a B or b indicates Blue, a G or g indicates Green, a R or r indicates Red, and a W or w indicates White. If the item number is not exactly seven characters display the appropriate error message. If the fourth character is not one of the valid color characters, display the appropriate error message. Use the sentinel value “X” to end the program.
#include <iostream>
#include <string>
using namespace std;
string itemCode = "";
int main() {
cout << "ENTER AN X TO STOP ITEM NUMBER DATA ENTRY." << endl << endl;
cout << "Enter Item Number: ";
getline(cin, itemCode);
while (itemCode != "x")
{
if (itemCode.length() == 7)
{
if (itemCode.find("B", 3) == "B")
{
cout << "Color is blue." << endl;
}
else if (itemCode.find("G", 3) == "G")
{
cout << "Color is green." << endl;
}
else if (itemCode.find("R", 3) == "R")
{
cout << "Color is Red." << endl;
}
else if (itemCode.find("W", 3) == "W")
{
cout << "Color is White." << endl;
}
else
cout << "Invalid color code found in item number.";
}
else
{
cout << "Item number must contain exactly 7 characters." << endl;
}
cout << "Enter Item Number: ";
getline(cin, itemCode);
}
cout << endl << "End of Program.";
return 0;
}
From glancing at your code, two obvious problems come to mind that's likely the source of your issues:
You're not checking if getline successfully grabbed the input.
Your usage of string::find's return value is wrong. You need to check for std::npos to see if there's a match or not. See here if you need more details.
For your first problem, you want something like:
while (getline(cin, zipCode) && zipCode != "x")
// ...
And removing the other getlines.
For the second, your usage should look something like:
if (zipCode.find("605", 0) != string::npos)
// ...
Your current if (zipCode.find("605", 0)) does not work because anything other than 0 or false is considered truthy. std::string::npos is typically defined as -1 which means the expression is true if the zipCode isn't found -- the opposite of your desired behavior.
Look, i have been writing this guessing game for a day and a half now. I keep getting errors related to using cin and getline together, and using a lot of advice I received from Stackoverflow, I thought I fixed all the bugs. Also, I realize it's best not to use >> and getline together, but to be honest, I don't know any other way, and I am afraid I will lose points if I use features of the language that our professor hasn't specifically taught us. So please just help me out, I have been ocd-ing like a maniac.
The game works correctly, and the game repeats, (I also know that using goto is evil, but this is just a very basic guessing game. I pinky promise not to ever use it in real life)
The problem arises when the game repeats a second time. After the game prompts the user to enter Y to continue, and they do, it will goto the start of my do-while loop, as it should. Stack unwinding be damned.
Next, it will read in the user input, ignoring white space at the stare of cin. But somehow, white space hops in at the end of my word after a few runs? I am baffled by this, as I thought that my loop which tests each index using the isalpha function would prevent this?
I could really use some concrete code to fix this, I have been up all night. Suggestions are fine but I don;t fully understand them and I am not allowed to use a good chunk of this languages features. Yes, I realize that is ridiculous, but I'm not my professor.
Here is a screenshot of the logical error:
Here is my code so far: You can read some of my comments to see the different paths this beast has been down:
#include<iostream>
#include<string>
#include <algorithm>
#include <iostream>
#include <string>
#include <functional>
#include <ctype.h>
using namespace std;
int main() {
string secretWord;
string secretWordClean = "";
string guessedLetters; //to be loaded with _ characters equal to length of secretWord
string incorrectlyGuessedChars = "";
char individualCharGuess;
char playAgain;
size_t countOfLetters = 0; //begine count at 0
size_t guessesRemaining;
int guessedUsed;
begin_game://label which we can use to bring us back to the start of the do-while loop at any time
//do{//start of the game
cout << "Please enter a secret word: ";
std::cin >> std::ws;
getline(std::cin, secretWord);
secretWord.erase(std::remove_if(secretWord.begin(), secretWord.end(), std::not1(std::ptr_fun(isalnum))), secretWord.end());
//std::cout << secretWord << "\n";
for(int i = 0; i < secretWord.length(); i++){
if (isalpha(secretWord[i])){
secretWordClean += secretWord[i];
}
}
secretWord = secretWordClean; //assign all alpha secret word string back to original variable for better readability
guessesRemaining = secretWord.length() * 2;
//cout << "Please enter a secret word: ";
//cin >> secretWord;
do{//start of the guessing portion of game
for(int i = 0; i < secretWord.length(); i++){
guessedLetters += "_"; //fills guessedLetters with blanks equal to the length of the secretWord
}
cout << "Please guess a letter, you have " << guessesRemaining << " guesses remaining!" << endl;
cin >> individualCharGuess;
for(int i = 0; i < secretWord.length(); i++){ //every complete iteration of this for loop = one single guess
if(secretWord[i] == individualCharGuess){
guessedLetters[i] = individualCharGuess; //will replace the spaces with the correct character, if guessed
countOfLetters++; //if any letter is guessed correctly, this indicator will be incrimented above 0
continue;
}
if(secretWord.find(individualCharGuess) == string::npos){
if(incorrectlyGuessedChars.find(individualCharGuess) == string::npos){
incorrectlyGuessedChars += individualCharGuess;
}
}
}
if(secretWord.compare(guessedLetters) == 0){
cout << "You win! The word was: " << secretWord << endl;
guessedUsed = ((secretWord.length() * 2) - guessesRemaining) + 1 ;
cout << "You used " << guessedUsed << " guesses." << endl;
cout << "Play again? Enter Y for Yes, or anything else to exit: ";
cin >> playAgain;
if(playAgain != 'Y'){
break; //exit the loop if user guesses all the letters and doesn't want to play again
}
else {
incorrectlyGuessedChars = "";
secretWordClean = "";
//continue;
goto begin_game;
}
}
guessesRemaining--; //we decriment our total guesses remaining if the user does not win the game or run out of guesses
if(countOfLetters > 0){
cout << "You have correctly guessed a letter!" << endl;
cout << "Here are the letters you have guessed correctly so far: ";
cout << guessedLetters << endl;
cout << "Here are the letters you have guessed incorrectly so far: ";
cout << incorrectlyGuessedChars << endl;
countOfLetters = 0; //reset the counter to prepare for next iteration of do-while loop
}
else if (guessesRemaining <= 0) {
cout << "You have run out of guesses!" << endl;
cout << "Here are the letters that you guessed correctly: ";
cout << guessedLetters << endl;
cout << "Here are the letters you guessed incorrectly: ";
cout << incorrectlyGuessedChars << endl;
cout << "The secret word was: " << secretWord << endl;
cout << "Play again? Enter Y for Yes, or anything else to exit: ";
cin >> playAgain;
if(playAgain != 'Y'){
break; //exit the loop if user guesses all the letters and doesn't want to play again
}
else {
secretWordClean = "";
incorrectlyGuessedChars = "";
//continue;
goto begin_game;
}
}
else {
cout << "You guessed wrong! Keep trying, " << guessesRemaining << " guesses to go!" << endl;
cout << "Here are the letters you have guessed correctly so far: ";
cout << guessedLetters << endl;
cout << "Here are the letters you have guessed incorrectly so far: ";
cout << incorrectlyGuessedChars << endl;
}
}while (secretWord.compare(guessedLetters) != 0 || guessesRemaining != 0); //use to repeat the request for a single char guess
return 0;
}
You should initialize with blanks (the _ character) the string before the loop starts, not at the beginning of every iteration, change your code to:
for (int i = 0; i < secretWord.length(); i++) {
guessedLetters += "_"; //fills guessedLetters with blanks equal to the length of the secretWord
}
do{ //start of the guessing portion of game
... rest of the code ...
if you don't, at every iteration of your game the guessedLetters variable is going to have more _ characters appended at the end of it, spoiling your final string comparison.
You should also clear the guessedLetters if you plan to play again:
else {
incorrectlyGuessedChars = "";
secretWordClean = "";
guessedLetters = ""; // Cleanup
//continue;
goto begin_game;
}
as a sidenote: gotos are a terrible programming practice and can render the code very unreadable/unmaintainable. I suggest redesigning your application without using gotos in a future revision.
This assignment given to me was to copy a Hangman game from our textbook and modify it to specific instructions in the book. I have spent a lot of hours trying to research this issue and find a reason why I keep getting the same error message that I do. Everywhere I have looked, everyone that have attempted to modify this code have attempted with arrays and have had the same luck that I have. I'm currently doing a chapter in Strings and was planning on doing most of my statement that is requested by the instructions in String.
What I need to modify in this code is to:
Keep track of all letters that are input by the user
Send an error message to the user if they input a letter that is already entered
The main issue I am having is that when I compile this code and put in the same letter that I have already put in, it terminates with the message:
terminate called after throwing an instance of 'std::out of range'
what(): basic_string::substr
#include <iostream>
#include <string>
using namespace std;
int main()
{
//declare variables
string origWord = " ";
string letter = " ";
char dashReplaced = 'N';
char gameOver = 'N';
int numIncorrect = 10;
string displayWord = "-----";
string usedLetter = " ";
string letterNotGuessedYet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int letterPlace = 0;
//get original word
do //begin loop
{
cout << "Enter a 5-letter word in uppercase: ";
getline(cin,origWord);
}while(origWord.length() != 5); //end do loop
//clear the screen
system("cls");
//start guessing
cout <<"Guess this word: " << displayWord << endl;
while(gameOver =='N')
{
cout << "Enter an uppercase letter: ";
cin >> letter;
//This provides the letterPlace value with the possition of the
//input letter by the user within letterNotGuessedYet
letterPlace = letterNotGuessedYet.find(letter,0);
//This statement determines if the letter input by the user is
//still in the letterNotGuessYet string.
if(letterNotGuessedYet.substr(letterPlace,1)== letter)
{
letterNotGuessedYet.replace(letterPlace, 1, "*");
//cout << endl << letterNotGuessedYet; //This tests that a letter is being replaced with an *
}
else
{
cout << "The letter " << letter << " has already been used. Choose another letter." << endl << endl;
}// end if
//search for the letter in the original word
for(int x = 0; x < 5; x++)
{
//if the current character matches
//the letter, replace the corresponding
//dash in the displayWOrd variable and then
//set the dashReplaced variable to 'Y'
if (origWord.substr(x,1) == letter)
{
displayWord.replace(x, 1, letter);
dashReplaced = 'Y';
}//end if
}//end for
//if a dash was replaced, check whether the
//displayWord variable contains any dashes
if (dashReplaced == 'Y')
{
//if the displayWord variable does not
//contain any dashes, the game is over
if (displayWord.find("-",0) == -1)
{
gameOver = 'Y';
cout << endl << "Yes, the word is " << origWord << endl;
cout << "Great guessing!" << endl;
}
else //otherwise, continue guessing
{
cout << endl<< "Guess this word: " << displayWord << endl;
dashReplaced = 'N';
}//end if
}
else //processed when dashReplaced contains 'N'
{
//minus 1 to the number of incorrect gueses left
numIncorrect += 1;
//if the number of incorrect guesses is 10,
//the game is over
if (numIncorrect == 10)
{
gameOver = 'Y';
cout << endl << "Sorry, the word is " << origWord << endl;
}//end if
}//end if
}//end while
//system("pause");
return 0;
}//end of main function
I believe the reason that I'm receiving this error has something to do with the below code:
//This provides the letterPlace value with the possition of the
//input letter by the user within letterNotGuessedYet
letterPlace = letterNotGuessedYet.find(letter,0);
//This statement determines if the letter input by the user is
//still in the letterNotGuessYet string.
if(letterNotGuessedYet.substr(letterPlace,1)== letter)
{
letterNotGuessedYet.replace(letterPlace, 1, "*");
//cout << endl << letterNotGuessedYet; //This tests that a letter is being replaced with an *
}
else
{
cout << "The letter " << letter << " has already been used. Choose another letter." << endl << endl;
}// end if
I am grateful for any assistance that you can bring my way.
The reason you're getting the error is because you are using the "letterPlace" value before you test to see if it was actually found or not. If "string::find" doesn't find anything it will return a value "string::npos". You need to test the letterPlace vairable for this value before trying to use it.
letterPlace = letterNotGuessedYet.find(letter,0);
// Check to see if this letter is still in the "letterNotGuessedYet string
if(letterPlace != string::npos)
{
// At this point the letter is in the letterNotGuessedYet string so let it go
letterNotGuessedYet.replace(letterPlace, 1, "*");
}
else
{
// The letter was not found which means it has already been guessed.
// Show error to the user here
cout << "The letter " << letter << " has already been used. Choose another letter." << endl << endl;
}