I'm quite new to C++ and my assignment is pretty tough. I must create a menu (in which I'm struggling quite badly), not only that but I should also read and display a textfile. So far, the only method I used only displays the first lines of the text file. Can you help me out? Thanks in advance.
The break function when added to the first case also makes the loop an infinite wall of texts! I dont know what to do..
// Assignment 1.cpp : Tally Ho Generator
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int runMenu;
int main()
{
int menuInput;
bool menu = true;
ifstream inFile;
string ABOUT;
// Menu Interface
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout << " The Tally Ho Probability Generator (MCD4720_Assignment 1)\n";
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout << " [1] End Testing the Program\n";
cout << " [2] Display About Information\n";
cout << " [3] Read and store data from files\n";
cout << " [4] Generate a Dice Tally Table\n";
cout << " [5] Save Tally Statistics to a file\n";
cout << " [6] Load Tally Statistics from a file\n";
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout << "Which Option would you like (1-6)\n";
cin >> runMenu;
// Menu Input Function
while (menu != false) {
switch (runMenu)
{
case 1:
{
inFile.open("C:\\Users\\William\\Documents\\MCD Assignment 4720 1\\TallyAbout.txt");
while (getline(inFile, ABOUT)) {
cout << ABOUT << endl;
inFile.close();
}
break;
}
case 2:
{}
case 3:
{}
case 4:
{}
case 5:
{}
case 6:
{}
default: {
cout << " Input unrecognized, please choose again \n";
cin >> runMenu;
break;
}
}
}
cin.ignore();
cin.get();
return 1;
}
So far, the only method I used only displays the first lines of the text file
That is because you close the file after reading the first line:
while (getline(inFile, ABOUT)) {
cout << ABOUT << endl;
inFile.close(); // <------ here !!
}
You do not need to close the file explicitly. The file is closed in the destructor of inFile.
The break function when added to the first case also makes the loop an infinite wall of texts! I dont know what to do..
That is because break breaks out of the switch. No other case will be handled. In particular, your default case where you ask for user input will not be executed. Actually you never modify the value of menu and while(menu != false) is an infinite loop. Move the part that has to be done for any case out of the switch:
while (menu != false) {
switch (runMenu)
{
case 1:
{
inFile.open("C:\\Users\\William\\Documents\\MCD Assignment 4720 1\\TallyAbout.txt");
while (getline(inFile, ABOUT)) {
cout << ABOUT << endl;
inFile.close();
}
break;
}
//...
default: {
cout << " Input unrecognized, please choose again \n";
break;
}
}
cin >> runMenu;
// put logic here, for example:
menu = (runMenu == 1);
}
You should modify the output accordingly. Currently it says " Input unrecognized, please choose again ", but if I understand correctly, the user has to choose to continue or not on every iteration. Also using one and not two variables for menu and runMenu would be less error-prone.
Try this:
case 1:
{
inFile.open("C:\\Users\\William\\Documents\\MCD Assignment 4720 1\\TallyAbout.txt");
while (getline(inFile, ABOUT)) {
cout << ABOUT << endl;
}
inFile.close();
break;
}
You are closing the file after you read the first line
The difference now is that you close the file after you read all lines
Related
Please note that I am a complete beginner at C++. I'm trying to write a simple program for an ATM and I have to account for all errors. User may use only integers for input so I need to check if input value is indeed an integer, and my program (this one is shortened) works for the most part.
The problem arises when I try to input a string value instead of an integer while choosing an operation. It works with invalid value integers, but with strings it creates an infinite loop until it eventually stops (unless I add system("cls"), then it doesn't even stop), when it should output the same result as it does for invalid integers:
Invalid choice of operation.
Please select an operation:
1 - Balance inquiry
7 - Return card
Enter your choice and press return:
Here is my code:
#include <iostream>
#include <string>
using namespace std;
bool isNumber(string s) //function to determine if input value is int
{
for (int i = 0; i < s.length(); i++)
if (isdigit(s[i]) == false)
return false;
return true;
}
int ReturnCard() //function to determine whether to continue running or end program
{
string rtrn;
cout << "\nDo you wish to continue? \n1 - Yes \n2 - No, return card" << endl;
cin >> rtrn;
if (rtrn == "1" and isNumber(rtrn)) { return false; }
else if (rtrn == "2" and isNumber(rtrn)) { return true; }
else {cout << "Invalid choice." << endl; ReturnCard(); };
return 0;
}
int menu() //function for operation choice and execution
{
int choice;
do
{
cout << "\nPlease select an operation:\n" << endl
<< " 1 - Balance inquiry\n"
<< " 7 - Return card\n"
<< "\nEnter your choice and press return: ";
int balance = 512;
cin >> choice;
if (choice == 1 and isNumber(to_string(choice))) { cout << "Your balance is $" << balance; "\n\n"; }
else if (choice == 7 and isNumber(to_string(choice))) { cout << "Please wait...\nHave a good day." << endl; return 0; }
else { cout << "Invalid choice of operation."; menu(); }
} while (ReturnCard()==false);
cout << "Please wait...\nHave a good day." << endl;
return 0;
}
int main()
{
string choice;
cout << "Insert debit card to get started." << endl;
menu();
return 0;
}
I've tried every possible solution I know, but nothing seems to work.
***There is a different bug, which is that when I get to the "Do you wish to continue?" part and input any invalid value and follow it up with 2 (which is supposed to end the program) after it asks again, it outputs the result for 1 (continue running - menu etc.). I have already emailed my teacher about this and this is not my main question, but I would appreciate any help.
Thank you!
There are a few things mixed up in your code. Always try to compile your code with maximum warnings turned on, e.g., for GCC add at least the -Wall flag.
Then your compiler would warn you of some of the mistakes you made.
First, it seems like you are confusing string choice and int choice. Two different variables in different scopes. The string one is unused and completely redundant. You can delete it and nothing will change.
In menu, you say cin >> choice;, where choice is of type int. The stream operator >> works like this: It will try to read as many characters as it can, such that the characters match the requested type. So this will only read ints.
Then you convert your valid int into a string and call isNumber() - which will alway return true.
So if you wish to read any line of text and handle it, you can use getline():
string inp;
std::getline(std::cin, inp);
if (!isNumber(inp)) {
std::cout << "ERROR\n";
return 1;
}
int choice = std::stoi(inp); // May throw an exception if invalid range
See stoi
Your isNumber() implementation could look like this:
#include <algorithm>
bool is_number(const string &inp) {
return std::all_of(inp.cbegin(), inp.cend(),
[](unsigned char c){ return std::isdigit(c); });
}
If you are into that functional style, like I am ;)
EDIT:
Btw., another bug which the compiler warns about: cout << "Your balance is $" << balance; "\n\n"; - the newlines are separated by ;, so it's a new statement and this does nothing. You probably wanted the << operator instead.
Recursive call bug:
In { cout << "Invalid choice of operation."; menu(); } and same for ReturnCard(), the function calls itself (recursion).
This is not at all what you want! This will start the function over, but once that call has ended, you continue where that call happened.
What you want in menu() is to start the loop over. You can do that with the continue keyword.
You want the same for ReturnCard(). But you need a loop there.
And now, that I read that code, you don't even need to convert the input to an integer. All you do is compare it. So you can simply do:
string inp;
std::getline(std::cin, inp);
if (inp == "1" || inp == "2") {
// good
} else {
// Invalid
}
Unless that is part of your task.
It is always good to save console input in a string variable instead of another
type, e.g. int or double. This avoids trouble with input errors, e.g. if
characters instead of numbers are given by the program user. Afterwards the
string variable could by analyzed for further actions.
Therefore I changed the type of choice from int to string and adopted the
downstream code to it.
Please try the following program and consider my adaptations which are
written as comments starting with tag //CKE:. Thanks.
#include <iostream>
#include <string>
using namespace std;
bool isNumber(const string& s) //function to determine if input value is int
{
for (size_t i = 0; i < s.length(); i++) //CKE: keep same variable type, e.g. unsigned
if (isdigit(s[i]) == false)
return false;
return true;
}
bool ReturnCard() //function to determine whether to continue running or end program
{
string rtrn;
cout << "\nDo you wish to continue? \n1 - Yes \n2 - No, return card" << endl;
cin >> rtrn;
if (rtrn == "1" and isNumber(rtrn)) { return false; }
if (rtrn == "2" and isNumber(rtrn)) { return true; } //CKE: remove redundant else
cout << "Invalid choice." << endl; ReturnCard(); //CKE: remove redundant else + semicolon
return false;
}
int menu() //function for operation choice and execution
{
string choice; //CKE: change variable type here from int to string
do
{
cout << "\nPlease select an operation:\n" << endl
<< " 1 - Balance inquiry\n"
<< " 7 - Return card\n"
<< "\nEnter your choice and press return: ";
int balance = 512;
cin >> choice;
if (choice == "1" and isNumber(choice)) { cout << "Your balance is $" << balance << "\n\n"; } //CKE: semicolon replaced by output stream operator
else if (choice == "7" and isNumber(choice)) { cout << "Please wait...\nHave a good day." << endl; return 0; }
else { cout << "Invalid choice of operation."; } //CKE: remove recursion here as it isn't required
} while (!ReturnCard()); //CKE: negate result of ReturnCard function
cout << "Please wait...\nHave a good day." << endl;
return 0;
}
int main()
{
string choice;
cout << "Insert debit card to get started." << endl;
menu();
return 0;
}
I am making a game and at the start, the player needs to assign points to different categories of their character (like Fallout's SPECIAL). Player input is currently read using std::cin. If the player inputs a letter instead of a number, std::cin will fail and crash the entire game.
I have attempted to check for failure with std::cin.fail() but no luck.
The relevant code which reads player input can be found below:
for(int i = 0; i < 5; i++) {
switch(i) {
case 0:
cout <<"\n\nStrength (How strong you are)";
cout <<"\nHow many points (you have " << total_SKILL_points << " left): ";
std::cin >>Strength;
if(std::cin.fail()) {
std::cin.clear();
cout <<"\n\nPlease enter a number!";
i--;
break;
}
total_SKILL_points = total_SKILL_points - Strength;
break;
// keeps going, that's why no closing } for switch or for loop.
Is there any proper way to check if a letter has been passed to std::cin?
You can clear the error flags and ignore the rest of the line if you get bad input.
#include <iostream>
#include <limits>
#include <list>
#include <string>
int main() {
int total_SKILL_points = 100;
int Strength;
while(true) {
std::cout << "\n\nStrength (How strong you are)\n"
"How many points (you have " << total_SKILL_points << " left): ";
if(std::cin >> Strength) { // check that cin is in a good state after extraction
// success
break;
} else {
// failure
if(std::cin.eof()) {
std::cout << "user aborted\n";
return 1;
}
std::cout << "\n\nPlease enter a number!";
// clear error flags
std::cin.clear();
// ignore rest of line
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
std::cout << Strength << "\n";
}
I think try and catch is a good option here. You could do something like:
for (int i = 0; i < 5; i++){
switch(i){
case 0:
std::cout <<"\n\nStrength (How strong you are)";
std::cout <<"\nHow many points (you have " << total_SKILL_points << " left): ";
std::cin >>Strength;
int intStrength;
try{
intStrength = std::stoi(Strength);
}
catch(std::invalid_argument const &e){
std::cout <<"\n\nPlease enter a number!" << std::endl;
i--;
break;
}
total_SKILL_points = total_SKILL_points - intStrength;
break;
I have used the method that Peter gave. Thanks for the help.
Peter's answer for those skimming this post:
Using std::cin.fail() doesn't work in your case because the stream itself is not in an error state. std::cin >> Strength has stopped reading because of invalid input and left the invalid input in the stream to be encountered on the next read operation - but it does NOT put the stream itself in an error state. Instead of using std::cin >> Strength, read a line of input using
std::getline(std::cin, astring)
where a string is of type std::string and parse the string to check if it has required input or other data.
Note: don't mix use of std::getline() with >> on the same stream.
I have written a program with several menus within it. I am now debugging the program and I wanted to include some input validation in the menu choices. However, for some reason, when it detects a wrong input it goes back to the beginning of the function with a goto statement (I know, bad practice :\) and It asks the user for a new input, but even if the input is right, it goes back to the case for non allowed inputs (default) no matter what. Does anyone have any idea of what's going on?
NOTE:
select_variable_check(vector<int> , int) is a function that checks if the value entered has been entered before if that is of any relevance, although I don't think it has anything to do with it.
void select(vector<int>&select_control) {
char select;
choices:
cin >> select;
int selectint = select;
bool check = select_variable_check(select_control, selectint);
switch (select) {
case ('1','2','3','4','5','6','7','8','9','10'):
if (check == false) {
string city = city_selection(selectint);
double xcoor = xcoor_selection(selectint);
double ycoor = ycoor_selection(selectint);
cout << "\n" << city << "\n";
select_control.push_back(selectint);
cout << "\n Enter next city: ";
cin >> select;
selectint = select;
}
else {
cout << "You have already selected that city, please select another one ";
cin >> select;
}
break;
case '99': {
cout << "TERMINATING" << endl;
Sleep(3000);
exit(0);
break;
}
case '100': {
cout << "input complete" << endl;
break;
}
default: {
cout << "not a valid value, please try again" << endl;
goto choices;
break;
}
}
The value of ('1','2','3','4','5','6','7','8','9','10') is '10', so that's the only value that will trigger that first case statement. The right way to write this is:
case '1':
case '2':
case '3':
...
Even with this change, though, '10' is a peculiar kind of character, and almost certainly not the right thing here.
Your code boils down to
start:
get_input
process_input
if good do something
else go to start
end:
Now when you enter bad input it goes back to start. Your input operation will fail again as the input stream is still in an error state so you do not get new input and since you have bad input you go back to start. To stop this loop you need to clear out the error flags on the stream and remove any input still in the buffer. That will make you default case look like
default: {
cout << "not a valid value, please try again" << endl;
cin.clear(); // removes error flags
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // flushes input buffer
goto choices;
break;
}
You will need to #include <limits> to use cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
I'm totally new and I don't know how else to ask this or what to even search for.
The case is this: I want to navigate through a menu with several sub-menus. In this example I'll just use "options" and a "game" to illustrate what I mean. Say you have a menu with 3 options.
1 - Start
2 - Options
3 - Quit
Choosing options should take you to another menu. Which would then look something like
1 - Difficulty
2 - Sound
3 - Back
Depending on where you go from here, there will be more sub menus obviously.
I've tried nesting do-while loops and all kinds of things but I just don't have enough understanding to know what it is I'm doing wrong.
Here is what I have so far:
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int choice;
do{
cout << "Main Menu\n";
cout << "Please make your selection\n";
cout << "1 - Start game\n";
cout << "2 - Options\n";
cout << "3 - Quit\n";
cout << "Selection: ";
cin >> choice;
switch(choice) {
case 1:
cout << "Pew pew!\n";
break;
case 2:
cout <<"????\n";
break;
case 3:
cout << "Goodbye!";
break;
default:
cout << "Main Menu\n";
cout << "Please make your selection\n";
cout << "1 - Start game\n";
cout << "2 - Options\n";
cout << "3 - Quit\n";
cout << "Selection: ";
cin >> choice;
}
} while(choice !=3);
system("PAUSE");
return EXIT_SUCCESS;
}
Which works like a regular menu. But I have no idea where to go from here. I consulted some books, but finding anything even remotely related to this was completely random. Any help or examples would be greatly appreciated.
What happened with nesting tons of loops just made all loops execute simultaneously every time. How do I keep this from happening? Making more choices? (choice1-2-3 etc ? or what?)
Ok guys. Thanks for all the help. This is what I ended up with in the end.
It runs as I want it to and by max_'s example and Mike B's commentary I think this works pretty well.
Thanks alot everyone =)
#include <iostream>
#include <cstdlib>
using namespace std;
void menu();
void mainMenu();
void optionsMenu();
void options();
int choice1 = 0;
int choice2 = 3;
int main(int argc, char** argv) {
menu();
return 0;
}
void menu(){
do {
choice2 = 0;
mainMenu();
switch(choice1) {
case 1:
cout << "Pew pew!\n";
break;
case 2:
options();
break;
case 3:
break;
}
} while(choice1 != 3);
}
void options(void) {
do {
optionsMenu();
switch(choice2){
case 1:
cout << "So difficult!\n";
break;
case 2:
cout << "Beep!\n";
break;
case 3:
break;
default:
break;
}
} while(choice2 != 3);
}
void mainMenu(void) {
cout << "Main Menu\n";
cout << "1 - Start game\n";
cout << "2 - Options\n";
cout << "3 - Quit\n";
cout << "Please choose: ";
cin >> choice1;
}
void optionsMenu(void) {
cout << "Options Menu\n";
cout << "1 - Difficulty\n";
cout << "2 - Sound";
cout << "3 - Back\n";
cout << "Please choose: ";
cin >> choice2;
}
How about this (dunno if it compiles though):
#include <cstdlib>
#include <iostream>
using namespace std;
int GetInput()
{
int choice;
cin >> choice;
return choice;
}
void DisplayMainMenu()
{
cout << "Main Menu\n";
cout << "Please make your selection\n";
cout << "1 - Start game\n";
cout << "2 - Options\n";
cout << "3 - Quit\n";
cout << "Selection: ";
}
void DisplayOptionsMenu()
{
cout << "Options Menu\n";
cout << "Please make your selection\n";
cout << "1 - Difficulty\n";
cout << "2 - Sound\n";
cout << "3 - Back\n";
cout << "Selection: ";
}
void Options()
{
int choice = 0;
do
{
system("cls");
DisplayOptionsMenu();
choice = GetInput();
switch(choice)
{
case 1:
cout << "difficulty stuff";
break;
case 2:
cout << "sound stuff";
break;
case 3:
break;
default:
break;
}
} while(choice!=3);
}
int main(int argc, char *argv[])
{
int choice = 0;
do
{
system("cls");
DisplayMainMenu();
choice = GetInput();
switch(choice) {
case 1:
cout << "Pew pew!\n";
break;
case 2:
Options();
break;
case 3:
cout << "Goodbye!";
break;
default:
break;
}
} while(choice!=3);
system("PAUSE");
return EXIT_SUCCESS;
}
I'd recommend that you change a few things here. Are you familiar with object-oriented design? If not, it's highly recommended that you read about that if you're looking to write code in C++ (Or just writing code in general, as it's a pretty major aspect of many programming languages)
Consider treating each of your menus and submenus as individual objects. Each time you enter the loop, use an object pointer to call a method that prints the current menu text.
Then, take the input from the user as normal, and change the menu object you're using now.
This is perhaps not the most ideal way to do a console menu, but it will give you a very strong grounding in how objected-oriented programming works.
I've attached an example :
#include <iostream>
#include <string>
class BaseMenu
{
public:
BaseMenu() { m_MenuText = "This shouldn't ever be shown!"; } // This is the constructor - we use it to set class-specific information. Here, each menu object has its own menu text.
virtual ~BaseMenu() { } // This is the virtual destructor. It must be made virtual, else you get memory leaks - it's not a quick explaination, I recommend you read up on it
virtual BaseMenu *getNextMenu(int iChoice, bool& iIsQuitOptionSelected) = 0; // This is a 'pure virtual method', as shown by the "= 0". It means it doesn't do anything. It's used to set up the framework
virtual void printText() // This is made virtual, but doesn't *have* to be redefined. In the current code I have written, it is not redefined as we store the menu text as a string in the object
{
std::cout << m_MenuText << std::endl;
}
protected:
std::string m_MenuText; // This string will be shared by all children (i.e. derived) classes
};
class FirstMenu : public BaseMenu // We're saying that this FirstMenu class is a type of BaseMenu
{
FirstMenu()
{
m_MenuText = "Main Menu\n" // What we are doing here is setting up the string to be displayed later
+ "Please make your selection\n" // What we are doing here is setting up the string to be displayed later
+ "1 - Start game\n" // What we are doing here is setting up the string to be displayed later
+ "2 - Options\n" // What we are doing here is setting up the string to be displayed later
+ "3 - Quit\n" // What we are doing here is setting up the string to be displayed later
+ "Selection: "; // What we are doing here is setting up the string to be displayed later
}
BaseMenu *getNextMenu(int choice, bool& iIsQuitOptionSelected) // This is us actually defining the pure virtual method above
{
BaseMenu *aNewMenu = 0; // We're setting up the pointer here, but makin sure it's null (0)
switch (choice) // Notice - I have only done "options". You would obviously need to do this for all of your menus
{
case 2:
{
aNewMenu = new SecondMenu; // We're creating our new menu object here, and will send it back to the main function below
}
case 3:
{
// Ah, they selected quit! Update the bool we got as input
iIsQuitOptionSelected = true;
}
default:
{
// Do nothing - we won't change the menu
}
}
return aNewMenu; // Sending it back to the main function
}
};
class SecondMenu : public BaseMenu
{
SecondMenu()
{
m_MenuText = "OptionsMenu\n"
+ "Please make your selection\n"
+ "1 - ????"
+ "2 - dafuq?";
}
BaseMenu *getNextMenu(int choice, bool& iIsQuitOptionSelected) // This is us actually defining the pure virtual method above
{
BaseMenu *aNewMenu = 0; // We're setting up the pointer here, but makin sure it's null (0)
switch (choice) // Notice - I have only done options. You would obviously need to do this for all of your menus
{
case 1:
{
aNewMenu = new FirstMenu; // We're creating our new menu object here, and will send it back to the main function below
}
break;
case 2:
{
aNewMenu = new FirstMenu; // We're creating our new menu object here, and will send it back to the main function below
}
break;
default:
{
// Do nothing - we won't change the menu
}
}
return aNewMenu; // Sending it back to the main function
}
};
int main (int argc, char **argv)
{
BaseMenu* aCurrentMenu = new FirstMenu; // We have a pointer to our menu. We're using a pointer so we can change the menu seamlessly.
bool isQuitOptionSelected = false;
while (!isQuitOptionSelected) // We're saying that, as long as the quit option wasn't selected, we keep running
{
aCurrentMenu.printText(); // This will call the method of whichever MenuObject we're using, and print the text we want to display
int choice = 0; // Always initialise variables, unless you're 100% sure you don't want to.
cin >> choice;
BaseMenu* aNewMenuPointer = aBaseMenu.getNextMenu(choice, isQuitOptionSelected); // This will return a new object, of the type of the new menu we want. Also checks if quit was selected
if (aNewMenuPointer) // This is why we set the pointer to 0 when we were creating the new menu - if it's 0, we didn't create a new menu, so we will stick with the old one
{
delete aCurrentMenu; // We're doing this to clean up the old menu, and not leak memory.
aCurrentMenu = aNewMenuPointer; // We're updating the 'current menu' with the new menu we just created
}
}
return true;
}
Note that this might be a bit complex for starting out. I strongly recommend you read the other answers people have posted. It should give you a few approaches on how to do it, and you can progress from the basic up to the more complex, examining each change.
Looking at what you are trying to do, I would change how you are ensuring the user still want's to play the game first. Look at using a while loop to check if a variable is true or false (people tend to use boolean variables(bool's) for this, an int set to 1 or 0 will do the same). That removes the need for the do-while. Reading up on control logic (if/else, while, for loops) and logical operators (&& - and, || - or, != - not equal to) is recommended. Control logic makes your code do different things, booleans are quick for checking yes/no scenarios and logical operators allow you to check multiple items in one if statement.
Some reading: Loops
Edit: Have more links for reading material, don't have the rep to post them.
Secondly, use another variable (int or whatever suits you) to track what screen you are on.
Based on this selection, display different options but still take input 1,2,3 to decide upon the next action.
In some terrible pseudo-code here is what I would lean towards:
main()
{
int choice
int screen = 1
bool running = true
while(running) {
//Screen 1, Main menu
if(screen == 1) {
cout << stuff
cout << stuff
cout << option 1
cout << option 2
cout << option 3
cout << selection:
cin >> choice
}
else if(screen == 2){
//options screen here
}
else {
//default/error message
}
//add some choice logic here
if(screen == 1 && choice == 3){
//being on screen one AND choice three is quit
running = false;
}
else if(screen == 1 && choice == 2){
//etc..
}
}
}
This is my first proper answer, all terrible criticism is well recieved.
First of all, thanks to everyone who helps me, it is much appreciated!
I am trying to store a string with spaces and special characters intact into MessageToAdd.
I am using getline (cin,MessageToAdd); and I have also tried cin >> MessageToAdd;.
I am so stumped! When I enter the sample input
Test
Everything works as intended. However if I were to use
Test Test Test
The whole console would just blink fast until I pressed CtrlC.
My style of putting variables at the top I've been told is obsolete. Please forgive me as I am still teaching myself and it's simply force of habit. I will be changing my style shortly after I get this solved :)
void AddMessage() {
ifstream myReadFile;
string str;
string MessageToAdd;
string myMessages[10];
int i; // of course my famous i
static string rowHtmlCloseTags;
static string rowHtmlOpenTags;
string replacement;
myReadFile.open("C:\\Users\\Andrews\\Documents\\Visual Studio 2010\\Projects\\computerclass\\Debug\\outages.htm",ios::in);
i = 0; //the start of my array
rowHtmlCloseTags = "</b></td>"; // value that I want to replace with nothing
rowHtmlOpenTags = "<td><b>";
if(!myReadFile) // is there any error?
{
cout << "Error opening the file! Aborting…\n";
exit(1);
}
if (myReadFile.is_open())
{
cout << endl;
while (!myReadFile.eof())
{
getline(myReadFile, str);
if (str == "<tr>")
{
getline(myReadFile, str); //get the next line cause thats where the <td><b>Outage Message</b></td> is.
size_t foundIndex = str.find(rowHtmlCloseTags); //does the sought string exist in this this line?
if (foundIndex != str.npos) //if not no position
str.replace(foundIndex, rowHtmlCloseTags.size(), replacement); //replace the string
else
std::cout << "Oops.. didn't find " << rowHtmlCloseTags << std::endl; //else throw a bitch
foundIndex = str.find(rowHtmlOpenTags); //does the sought string exist in this this line?
if (foundIndex != str.npos) //if not no position
str.replace(foundIndex, rowHtmlOpenTags.size(), replacement); //replace the string
else
std::cout << "Oops.. didn't find " << rowHtmlOpenTags << std::endl; //else throw a bitch
myMessages[i]=str;
i++;
}
}
}
system("cls");
i=0;
while (i < 10)
{
cout << i << ") " << myMessages[i] << endl;
i++;
if (myMessages[i]=="")
{
break;
}
}
myReadFile.close();
cout << endl;
cout << endl;
cout << "Enter the message you would like to see on the reader board.\n";
cout << "Or enter 911 to go back to the main menu: ";
cin.ignore(1080);
getline (cin,MessageToAdd);
if (str == "911") //go back to the main menu
{
system("cls");
mainMenu();
}
else //insert the message into a blank spot in the array
{
i=0;
while (i < 10)
{
if (myMessages[i].empty())
{
myMessages[i]=MessageToAdd;
break;
}
else
{
i++;
}
}
}
//now rebuild the htm file with the new array
CreateHtmlFile(myMessages);
}
I'll tell you one thing that's immediately wrong with your code, not your specific problem but a hairy one nonetheless.
I'm presuming that your mainMenu() function is calling this one. In that case, you appear to be under the misapprehension that:
if (str == "911") //go back to the main menu
{
system("cls");
mainMenu();
}
will return to your menu. It will not do that. What it will do is to call your main menu code afresh and eventually you will run out of stack space.
I suspect that what you should be doing is having a loop in mainMenu() and that code above should just use return; rather than calling mainMenu() recursively.
That and the fact that I think you should be comparing MessageToAdd against "911" rather than str.
Another thing I would do would be to put some temporary debug code in:
cout << "DEBUG A\n";
i=0;
while (i < 10)
{
cout << "DEBUG B " << i << "\n";
if (myMessages[i].empty())
{
cout << "DEBUG C\n";
myMessages[i]=MessageToAdd;
break;
}
else
{
i++;
cout << "DEBUG D " << i << "\n";
}
cout << "DEBUG E\n";
}
cout << "DEBUG F\n";
and see what gets printed. Of course, you could trace the execution in a debugger but that would require you to do the work yourself. If you just post the output (first 100 lines if it's huge), then we can probably tell you what's wrong easily.
Actually, I think your problem is the cin.ignore. When I run your code, nothing works, neither Test nor Test Test Test. That's because it's ignoring the first 1080 characters I'm trying to input. Proof can be seen when you change those statements to:
cin.ignore(1);
getline (cin,MessageToAdd);
cout << MessageToAdd << "\n";
and you get est output when you enter test.
Take out the ignore line and try again. I'm not certain of this since you seem to indicate that Test works but I can't see this as being correct.
So here's what you need to do (at a bare minimum):
get rid of the cin.ignore altogether.
use return rather than mainMenu().
use if (MessageToAdd == "911") instead of if (str == "911").
let us know how it goes then.