C++ FileIO to read and write into objects variables - c++

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

Related

C++ Anagram Solver speed optimization

I have decided to make an anagram solver for my dad. I am quite new to programming, but i figured I can still make it. My finished product works, but it is really slow, for instance it took about 15+ mins to find all combinations of 8 characters. I am looking for ways to optimize it / make it faster.
Working with MinGW c++ compier, on Clion 2019.3.4, cpu: i7 9700k, and RAM: 16GB/3200mhz.
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
//Menu for interacting with user, not really important
void menu() {
cout << "=========================" << endl;
cout << "======== !WOW! ==========" << endl;
cout << "=========================" << endl;
cout << "1 ... INSERT" << endl;
cout << "2 ... PRINT" << endl;
cout << "3 ... LIMIT WORD LENTGH" << endl;
cout << "4 ... NEW GAME" << endl;
cout << "0 ... EXIT" << endl;
cout << "=========================" << endl;
cout << "Select: ";
}
//Function to find all possible combinations from letters of a given string
void get(vector<string> &vec, string str, string res) {
vec.push_back(res);
for (int i = 0; i < str.length(); i++)
get(vec, string(str).erase(i, 1), res + str[i]);
}
//Only for testing purposes
void printVec(vector<string> vec) {
for (int i = 0; i < vec.size(); i++) {
cout << vec[i] << " ";
}
}
//Function to check if a given word exists in given .txt file
bool checkWord(vector<string> &vec2, string filename, string search) {
string line;
ifstream myFile;
myFile.open(filename);
if (myFile.is_open()) {
while (!myFile.eof()) {
getline(myFile, line);
if (line == search) {
vec2.push_back(line);
return true;
}
}
myFile.close();
} else
cout << "Unable to open this file." << endl;
return false;
}
int main() {
int selection;
bool running = true;
string stringOfChars;
vector<string> vec;
vector<string> vec2;
do {
menu();
cin >> selection;
switch (selection) {
case 1:
cout << "Insert letters one after another: ";
cin >> stringOfChars;
get(vec, stringOfChars, ""); //fill first vector(vec) with all possible combinations.
break;
case 2:
for (int i = 0; i < vec.size(); i++) {
if (checkWord(vec2, "C:/file.txt", vec[i])) { //For each word in vector(vec) check if exists in file.txt, if it does, send it in vector(vec2) and return true
//Reason for vec2's existence is that later I want to implement functions to manipulate with possible solutions (like remove words i have already guessed, or as shown in case 3, to limit the word length)
cout << vec[i] << endl; //If return value == true cout the word
}
}
break;
case 3:
int numOfLetters;
cout << "Word has a known number of letters: ";
cin >> numOfLetters;
for (int i = 0; i < vec2.size(); i++) { /*vec2 is now filled with all the answers, we can limit the output if we know the length of the word */
if (vec2[i].length() == numOfLetters) {
cout << vec2[i] << endl;
}
}
break;
case 4:
vec.clear();
vec2.clear();
break;
case 0:
running = false;
break;
default:
cout << "Wrong selection!" << endl;
break;
}
cout << endl;
} while (running);
return 0;
}
file.txt is filled with all words in my language, It's alphabetically ordered and it's 50mb in size.
aachecnska
aachenskega
aachenskem
aachenski
.
.
.
bab
baba
babah
.
.
.
Any recommendations or off topic tips would be helpful. One of my ideas is to maybe separate file.txt in smaller files, like for example putting lines that have same starting letter in their own file, so A.txt would only contain words that start with A etc... And than change the code accordingly.
this is where you need to use a profiler. on Linux, my favorite is kcachgrind
http://kcachegrind.sourceforge.net/html/Home.html
it gives you line-by-line timing information and tells you which part of the code you should optimize the most.
of course, there are many profilers available, including commercial ones.

Check letters against the word of an arbitrary size in a Hangman game

Currently I am working on a hangman game, I had previously coded it to only work for a 5 letter word, but now would like to make it handle any length of word, how could I change this code to make it work how I want it to?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <stdlib.h>
#include <cstdlib>
using namespace std;
int main()
{
string word;
int tries;
string guess;
string wordguess;
string output;
cout << "Enter a word for player two to guess: ";
cin >> word;
system("CLS");
cout.flush();
cout << "Guess the word!" << endl;
for (int i = 0; i < word.length(); i++)
{
cout << "_ ";
}
cout << "Enter a letter: ";
cin >> guess;
for (int tries = 5; tries > 0; tries--)
{
if (guess[0] == word[0]) {
output[0] = word[0];
cout << "You guessed the first letter! Good job!" << endl;
}
if (guess[0] == word[1]) {
output[2] = word[1];
cout << "You guessed the second letter! Good job!" << endl;
}
if (guess[0] == word[2]) {
output[4] = word[2];
cout << "You guessed the third letter! Good job!" << endl;
}
if (guess[0] == word[3]) {
output[6] = word[3];
cout << "You guessed the fourth letter! Good job!" << endl;
}
if (guess[0] == word[4]) {
output[8] = word[4];
cout << "You guessed the fifth letter! Good job!" << endl;
}
cout << output << endl;
cout << "You have " << tries << " tries left. Take a guess at the word: " << endl;
cin >> wordguess;
if (wordguess == word)
{
cout << "Congratulations, you guessed the word correctly!" << endl;
break;
}
}
system("pause");
return 0;
}
As you can tell I was checking each position from 0 to 4 (first through fifth letter). I know there are plenty of ways that I could have coded this better but as you can guess, I am new to coding and this is the way I thought of it. Please note this is still a work in progress so it is not fully complete. Any help would be great!
When designing an algorithm, think of how you would do this by hand, without a computer. Then let the code do the same.
If you were checking your friend's guess against a word written on sand, you would probably go about it like this:
go through the written pattern character by character, pronouncing your word in memory
for each letter, check if it is equal to the guess
if it is
replace the placeholder with it
memorize that your friend guessed right.
Also note if there are any placeholders left
if there aren't, your friend wins
finally, if your friend didn't guess right, score them a penalty point and check if they lose
Now, all that leaves is to put this down in C++. The language provides all sorts of entities - let's check which ones fit ours needs the best:
the word and the current pattern - strings of a fixed size
bits to memorize:
whether the current guess is right - bool
placeholders left - int
penalty points (or, equivalently, attempts left) - int
parts of the algorithm:
looping over a string - for loop of one of a few kinds
we need to replace the character in the pattern at the same index as the guessed letter in the word. So, we need to have the index when looping. Thus the flavor with the index variable, for(std::string::size_type i = 0; i < str.size(); ++i) probably fits the best.
// Example program
#include <iostream>
#include <string>
using namespace std;
class my_game
{
private:
string congrats_array[15] = {"first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "nineth", "tenth", "eleventh", "twelfth", "thirteenth", "fourteenth", "fifteenth"};
string word_to_guess;
int tries_left;
int word_length;
int letters_guessed_count;
string guessed_letters;
void check_letter(char letter);
void print_current_word_state();
public:
my_game();
void begin_the_game();
void play_the_game();
};
my_game::my_game()
{
}
void my_game::begin_the_game()
{
cout << "Enter a word for player to guess: " << endl;
cin >> word_to_guess;
system("CLS");
cout.flush();
cout << "Enter the tries amount!\n" << endl;
cin >> tries_left;
word_length = word_to_guess.size();
guessed_letters = "_";
letters_guessed_count = 0;
for(int i = 0; i < word_length - 1; i++){
guessed_letters += "_";
}
}
void my_game::play_the_game()
{
cout << "Guess the word!" << endl;
char letter;
for(int i = 0; i < tries_left; i++)
{
cout << guessed_letters << endl;
cout << "Enter a letter: " << endl;
cin >> letter;
check_letter(letter);
if(letters_guessed_count == word_length){
cout << "Congrats! You won!" << endl;
return;
}
}
cout << "You lose" << endl;
}
void my_game::check_letter(char letter)
{
for(int i = 0; i < word_length; i++)
{
if(word_to_guess[i] == letter && guessed_letters[i] != letter)
{
guessed_letters[i] = letter;
letters_guessed_count++;
cout << "You guessed the" << congrats_array[i] <<"letter! Good job!" << endl;
}
}
}
int main()
{
my_game game;
game.begin_the_game();
game.play_the_game();
}
So, in short what you need to do this with words of any arbitrary length is to use string's .substr() function and the stringstream library's .str() and << and >> operators. This version of your code uses a function that inserts a correctly guessed character at the appropriate indexed location. This will gradually replace the "_________" with letters at the correct places. This is much easier to do in Java, but stringstream is a good library I would highly recommend getting familiar with it. I'll leave the problem of how to handle multiple instances of a guessed character up to you (ie 'i' in "bibliography")
#include <string>
using std::string;
#include <sstream>
using std::stringstream;
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
string newString(string, int, string);
int main()
{
string word;
string guess;
int tries;
string output;
string input;
cout << "Enter word for player 2 to guess: ";
cin >> word;
stringstream ss;
//---------- fills the stream with "_"s matching the length of word
for(int i = 0; i < word.length(); i++)
ss << "_";
//----------- assigns the initial value of "___..." to output
ss >> output;
//----------- sets up the loop
tries = 5;
bool found = false;
for(int i = 0; i < 5; i++)
{
cout << "\nTry " << i << " of 5: Enter a letter or guess the word: ";
cin >> input;
if(input == word)
{
cout << "Congratulations, you guessed the word correctly!" << endl;
break;
}
//------------------ else, proceed with replacing letters
if(word.find(input) != std::string::npos)
{
size_t position = word.find(input); // finds index of first instance of the guessed letter
cout << "You guessed the " << position+1 << " letter! Good job!" << endl; // since strings start at index 0, position+1
//------- replaces appropriate "_" with the guessed letter
output = newString(input, position, output);
cout << "\n" << output;
// Around here you'll want to set up a way to deal with multiple instances
// of the same letter
}
else
cout << "Incorrect guess" << endl;
}
return 0;
}
//---------------------------------------------------
string newString(string guess, int index, string word)
{
string NewString;
stringstream temp;
//---------- hack up the string into sections before and after the index
string before = word.substr(0, index);
string after = word.substr(index+1, word.length() - index+1);
//---------------- populates the new stringstream and assigns it to the result
temp << before << guess << after;
NewString = temp.str();
return NewString;
}

C++ Erase-Remove Idiom not working properly?

This post is a continuation on my post from yesterday: How to output a vector.
So I am in the process of writing a short program that will take a list of strings into a vector, export them to a file, view them before outputting them and lastly remove them if possible. I have managed to get all of the functions working properly except for case 3 (remove a book from the list). The errors I am getting in visual studio as follows:
1.) "No instance of the overloaded function "remove" matches the argument list. [LN 76]
2.) "'Remove': function does not take 2 arguments". [LN 76]
As you can probably tell, I am trying to remove by value instead of index. I am still learning here so be gentle, but why exactly am I getting these errors?
Here is my full code:
#include <iostream>
#include <cctype>
#include <ctype.h>
#include <algorithm>
#include <string>
#include <math.h>
#include <windows.h>
#include <iomanip>
#include <vector>
#include <iostream>
#include <sstream>
#include <fstream>
#include <istream>
// common namespace
using namespace std;
int main()
{
int option;
bool iWannaLeave = false;
vector<string> bookCollection;
string entryVal = " ";
int anotherOption;
do
{
cout << "Welcome to MyBook! - A text recorder framework application." << endl;
cout << "-----------------------------------------------------------" << endl;
cout << "Main Menu:" << endl;
cout << "1 - Add a book to the collection." << endl;
cout << "2 - Display all books currently in the collection." << endl;
cout << "3 - Remove books from the collection." << endl;
cout << "4 - Write stored collection to file." << endl;
cout << "5 - Quit" << endl;
cout << "Make your selection: ";
cin >> option;
cin.ignore();
switch (option)
{
case 1:
{
bool wannaMoreBooks = false;
// the next loop will execute at least one time so you could enter a book
do
{
wannaMoreBooks = false;
cout << "Add a book title to the collection: ";
getline(cin, entryVal);
bookCollection.push_back(entryVal);
cout << "Would you like to enter another book?(1 - yes, 0 - no): ";
cin >> anotherOption;
cin.ignore();
if (anotherOption == 1) wannaMoreBooks = true;
} while (wannaMoreBooks == true);
}
break;
case 2:
{
for (int i = 0; i < bookCollection.size(); i++)
cout << bookCollection[i] << " | ";
cout << endl;
break;
}
case 3:
{
string vecVal;
cout << "Enter the value you would like to remove: " << endl;
cin >> vecVal;
bookCollection.erase(remove(bookCollection.begin(), vecVal), bookCollection.end());
}
// remove a book from the collection
break;
case 4:
{
ofstream fileOut("Collection.txt");
fileOut << "Your MyBook Collection: [Begin] - | ";
auto first = true;
for (string x : bookCollection)
{
if (!first) { fileOut << " | "; }
first = false;
fileOut << x;
}
fileOut << " | - [End]" << endl;
cout << "Collection.txt has been successfully written." << endl;
break;
}
case 5:
{
//Nested IF to kill program properly
int quitVar;
cout << "Are you sure you want to exit the program?: ";
cin >> quitVar;
cin.ignore();
if (quitVar == 1)
{
cout << "The program will now be terminated." << endl;
iWannaLeave = true;
}
else if (quitVar == 0) cout << "Returning to the main menu." << endl;
}
break;
}
} while (iWannaLeave == false);
return 0;
}
I am aware that this is no where near perfect code so in addition to finding out why I am getting these errors I would also like some constructive criticism as to how I can improve.
Additionally: If I wanted to go about using functions in a header file as opposed to a switch, would I just move the case contents to a header file?
Thanks in advance! :)
Virtually all STL-functions take one or more pairs of iterators. Since you just pass begin, there is no viable overload. You need to call
remove(bookCollection.begin(), bookCollection.end(), vecVal)
It is always a good idea to check the reference, which typically also contains a basic usage example.

Why can't I print out my string array c++?

I have written this code and I am supposed to read in a txt file and read every other line in the txt file to the string array bookTitle[ARRAY_SIZE] and the other every other line to bookAuthor[ARRAY_SIZE]. Here is my code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int ARRAY_SIZE = 1000;
string bookTitle [ARRAY_SIZE];
string bookAuthor [ARRAY_SIZE];
int loadData(string pathname);
void showAll(int count);
//int showBooksByAuthor (int count, string name);
//int showBooksByTitle (int count, string title);
int main ()
{
int number, numOfBooks;
char reply;
string bookTitles, authorName, backupFile;
cout << "Welcome to Brigham's library database." << endl;
cout << "Please enter the name of the backup file:";
cin >> backupFile;
numOfBooks = loadData (backupFile);
if (numOfBooks == -1) {
cout << endl;
} else {
cout << numOfBooks << " books loaded successfully." << endl;
}
cout << "Enter Q to (Q)uit, Search (A)uthor, Search (T)itle, (S)how All:";
cin >> reply;
do {
switch (reply) {
case 'a':
case 'A':
cout << "Author's name: ";
cin >> authorName;
showBooksByAuthor (numOfBooks, authorName);
cout << endl;
break;
case 'q':
case 'Q':
cout << endl;
break;
case 's':
case 'S':
showAll(numOfBooks);
break;
case 't':
case 'T':
cout << "Book title: ";
cin >> bookTitles;
showBooksByTitle(numOfBooks, bookTitles);
cout << endl;
break;
default:
cout << "Invalid input" << endl;
break;
}
} while (reply != 'q' && reply != 'Q');
while (1==1) {
cin >> number;
cout << bookTitle[number] << endl;
cout << bookAuthor[number] << endl;
}
}
int loadData (string pathname){
int count = 0, noCount = -1;
ifstream inputFile;
string firstLine, secondLine;
inputFile.open(pathname.c_str());
if (!inputFile.is_open()) { //If the file does not open then print error message
cout << "Unable to open input file." << endl;
return noCount;
}
for (int i = 0; i <= ARRAY_SIZE; i++) {
while (!inputFile.eof()) {
getline(inputFile, firstLine);
bookTitle[i] = firstLine;
getline(inputFile, secondLine);
bookAuthor[i] = secondLine;
cout << bookTitle[i] << endl;
cout << bookAuthor[i] << endl;
count++;
}
}
return count;
}
void showAll (int count) {
for (int j = 0; j <= count; j++) {
cout << bookTitle[j] << endl;
cout << bookAuthor[j] << endl;
}
}
So I have the loadData function which I am pretty sure is my problem. When I have it print out each string[ith position] while running the loadData function it prints out each title and author just as it appears in the txt file. But then when I run the void showAll function which is supposed to be able to print the entire txt doc to the screen it doesn't work. Also just I checked to see if the strings were actually stored in memory and they were not. (After my do while loop I have a while loop that accepts input of type int and then prints the string array of the [input position]. This prints nothing. So what do I have to do to actually store each line to a different position in the string array(s)? Feel free to correct my code but it isn't pretty yet considering I still have two functions that I haven't done anything too. (Commented out).
You main problem is that you try to read you data using two loops rather than just one! You want read until either input fails or the array is filled, i.e., something like this:
for (int i = 0;
i < ARRAY_SIZE
&& std::getline(inputFile, bookTitle[i])
&& std::getline(inputFile, bookAuthor[i]); ++i) {
}
The problem with the original code is that it never changes the index i and always stores values into the cell with index 0. Since the input isn't checked after it is being read, the last loop iteration fails to read something and overwrites any earlier stored value with an empty value. Once reading of the stream fails the outer loop iterates over all indices but doesn't do anything as the check to the inner loop is always false.

On finding vowels and capitals char in the beginning of a string?

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.