I have a code that is supposed to use user input to take an order of a pizza.
#include<iostream>
#include<string>
using namespace std;
int main()
{
double totalCosts = 0;
// PIZZA
cout << "What size is your first pizza?\n"
"small: $8.00\n"
"medium: $10.00\n"
"large: $12.00\n";
string currentSize = "";
getline(cin, currentSize);
cout << "\n";
if(currentSize == "small")
{
totalCosts += 8;
}
else if(currentSize == "medium")
{
totalCosts += 10;
}
else if(currentSize == "large")
{
totalCosts += 12;
}
else
{
cout << "invalid size: " << currentSize;
return 0;
}
string pizzaToppings = "";
cout << "Choose from the following toppings:\n"
"onions: $1.00\n"
"peppers: $1.20\n"
"ham: $1.50\n"
"hamburger: $1.25\n"
"pepperoni: $1.55\n"
"salami: $1.63\n"
"sausage: $1.44\n";
getline(cin, pizzaToppings);
cout << "\n";
if(pizzaToppings.find("onions") != string::npos)
{
totalCosts += 1;
}
else if(pizzaToppings.find("peppers") != string::npos)
{
totalCosts += 1.2;
}
else if(pizzaToppings.find("ham") != string::npos)
{
totalCosts += 1.5;
}
else if(pizzaToppings.find("hamburger") != string::npos)
{
totalCosts += 1.25;
}
else if(pizzaToppings.find("pepperoni") != string::npos)
{
totalCosts += 1.55;
}
else if(pizzaToppings.find("salami") != string::npos)
{
totalCosts += 1.63;
}
else if(pizzaToppings.find("sausage") != string::npos)
{
totalCosts += 1.44;
}
else
{
cout << "Choose at least one valid topping";
return 0;
}
// DELIVERY AND FINAL PRINTOUT
string needToDeliver = "";
cout << "Do you want delivery? yes/no\n";
getline(cin, needToDeliver);
cout << "\n";
if(needToDeliver == "yes")
{
totalCosts += 3;
cout << "What is your address?";
getline(cin, needToDeliver); // address doesn't matter
}
cout << "Your total cost is: $" << totalCosts << ". Thank you for buying C++ Pizza.";
return 0;
}
This code gives the following output:
What size is your first pizza?
small: $8.00
medium: $10.00
large: $12.00
invalid size:
What I think is happening is the first getline function is not waiting for any user input, and is instead inputing an empty string. Why is it doing this?
Related
I'm sorry for the vague title, but I don't know what else to say.
Here is my program:
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <fstream>
#include <vector>
using namespace std;
int
main (int argc, char **argv)
{
//string fin;
string ttl, dscp, ext;
string west = "w";
string east = "e";
string north = "n";
string south = "s";
int numRooms;
//string argv[1] = filename;
class Room
{
public:string title;
string description;
string exits;
int exitWest = -1;
int exitNorth = -1;
int exitEast = -1;
int exitSouth = -1;
int numExits;
};
ifstream fin;
fin.open (argv[1]);
//cin.ignore();
int t = 0;
while (fin)
{
string tilde;
string tester;
tester = "~";
cin >> tilde;
if (tilde == tester)
{
t = t + 1;
}
(numRooms = t / 3);
}
Room *roomArrayPtr = new Room[numRooms];
fin.clear ();
while (fin)
{
for (int l = 0; l < numRooms; l++)
{
getline (fin, ttl, '~');
roomArrayPtr[l].title = ttl;
getline (fin, dscp, '~');
roomArrayPtr[l].description = dscp;
getline (fin, ext, '~');
stringstream sin;
sin << ext;
string x;
int y;
while (sin >> x >> y)
{
if (x == west)
{
roomArrayPtr[l].exitWest = y;
}
if (x == south)
{
roomArrayPtr[l].exitSouth = y;
}
if (x == north)
{
roomArrayPtr[l].exitNorth = y;
}
if (x == east)
{
roomArrayPtr[l].exitEast = y;
}
}
sin.clear ();
int numext;
numext = (ext.size ()) / 3;
roomArrayPtr[l].numExits = numext;
}}
//(read in file again populate roomarrayptr w while loop and getline)
//roomArrayPtr[index].title = line;
//roomArrayPtr[index].description=line;
//close files, while loop that reads in user input from stdin, delete pointers w (delete[] roomArrayPtr;)
//if (exitsarray[i].size() > 2){
char command;
char newcommand;
cout << ">";
cin >> command;
int currentroom = 0;
int newroom;
bool keepgoing = true;
//string dir1;
while (keepgoing)
switch (command)
{
// stringstream ss;
case 'l':
cout << roomArrayPtr[currentroom].title << endl;
cout << roomArrayPtr[currentroom].description << endl;
cout << endl;
//if (roomArrayPtr[currentroom].numExits < 2) {
cout << "Exits: ";
if (roomArrayPtr[currentroom].exitWest > -1)
{
cout << "w";
}
if (roomArrayPtr[currentroom].exitNorth > -1)
{
cout << "n";
}
if (roomArrayPtr[currentroom].exitSouth > -1)
{
cout << "s";
}
if (roomArrayPtr[currentroom].exitEast > -1)
{
cout << "e";
}
/*else {
cout << "Exits: " ;
for (int k = 0; k < numExits; k++){
cout << exitdirection << " ";
}
}*/
//string newcommand;
cin >> newcommand;
//int newroom;
switch (newcommand)
{
case 'w':
if (roomArrayPtr[currentroom].exitWest == -1)
{
cout << "You can't go WEST!" << endl;
}
else
{
newroom = roomArrayPtr[currentroom].exitWest;
cout << "You moved WEST." << endl;
}
break;
case 'e':
if (roomArrayPtr[currentroom].exitEast == -1)
{
cout << "You can't go EAST!" << endl;
}
else
{
newroom = roomArrayPtr[currentroom].exitEast;
cout << "You moved EAST." << endl;
}
break;
case 'n':
if (roomArrayPtr[currentroom].exitNorth == -1)
{
cout << "You can't go NORTH!" << endl;
}
else
{
newroom = roomArrayPtr[currentroom].exitNorth;
cout << "You moved NORTH." << endl;
}
break;
case 's':
if (roomArrayPtr[currentroom].exitSouth == -1)
{
cout << "You can't go SOUTH!" << endl;
}
else
{
newroom = roomArrayPtr[currentroom].exitSouth;
cout << "You moved SOUTH." << endl;
}
break;
}
break;
case 'q':
keepgoing = false;
return 0;
break;
currentroom = newroom;
}
}
Whenever I run it, it compiles, but nothing happens. I tried putting in some random cout << "testing1" "testing2" scattered throughout, but none of those even showed up. I put it immediately after the { after int main and it still didn't show up. What's going on?
I tried putting in some random cout << "testing1" "testing2" scattered throughout, but none of those even showed up. I put it immediately after the { after int main and it still didn't show up.
you are reading the wrong file
int t = 0;
while (fin)
{
string tilde;
string tester;
tester = "~";
cin >> tilde; <<<<===== i assume you mean fin
if (tilde == tester)
{
t = t + 1;
}
(numRooms = t / 3);
}
I am a beginner at coding and learning C++. I just wrote a code that asks the user to log in, Register, or exit.
I thought doing it through functions would be easier. While checking for the constraints of the username and password for registration(referred to as "Rusr" and "Rpwd" here) the code I've written to check if lowercase, uppercase, and digits are not working. I tried to do it with character array as well but that didn't work. Would really appreciate some help with this.
Here's my code below for further reference:
#include <fstream>
#include <iostream>
#include <string.h>
using namespace std;
bool isvalidName(string Rusr)
{
if(Rusr.length() > 5 && Rusr.length() < 20) // length constraint
return true;
else
cout << "Invalid username" << endl;
{
for(int i = 0; i < Rusr.length(); i++) // check if digits are present
{
if(isdigit(Rusr[i]) == true)
return true;
if(true)
break;
else
cout << "Invalid username";
}
}
{
for(int i = 0; i < Rusr.length(); i++) // check for lowercase
{
if(islower(Rusr[i])) {
return true;
}
if(true)
break;
else
cout << "Invalid username";
}
}
{
for(int i = 0; i < Rusr.length(); i++) // check for uppercase
{
if(isupper(Rusr[i])) return true;
if(true)
break;
else
cout << "Invalid username";
}
}
}
int isvalidPwd(string Rpwd) {
{
if(Rpwd.length() > 8 && Rpwd.length() < 20)
return true;
else
cout << "Invalid password " << endl;
}
{
for(int i = 0; i < Rpwd.length(); i++) {
if(isdigit(Rpwd[i]) == true) return true;
if(true)
break;
else
cout << "Invalid password";
}
}
{
if(!((Rpwd.find("#") == string::npos) ||
(Rpwd.find("#") == string::npos) ||
(Rpwd.find("!") == string::npos) ||
(Rpwd.find("$") == string::npos) ||
(Rpwd.find("%") == string::npos) ||
(Rpwd.find("^") == string::npos) ||
(Rpwd.find("&") == string::npos) ||
(Rpwd.find("*") == string::npos) ||
(Rpwd.find("(") == string::npos) ||
(Rpwd.find(")") == string::npos) ||
(Rpwd.find("_") == string::npos) ||
(Rpwd.find("+") == string::npos) ||
(Rpwd.find("|") == string::npos) ||
(Rpwd.find(">") == string::npos) ||
(Rpwd.find("<") == string::npos) ||
(Rpwd.find("?") == string::npos) ||
(Rpwd.find("/") == string::npos) ||
(Rpwd.find("~") == string::npos) ||
(Rpwd.find(".") == string::npos) ||
(Rpwd.find(",") == string::npos)))
return true;
else
cout << "should contain special characters" << endl;
}
for(int i = 0; i < Rpwd.length(); i++) {
if(islower(Rpwd[i])) return true;
if(true)
break;
else
cout << "should contain lower case";
}
{
for(int i = 0; i < Rpwd.length(); i++) {
if(isupper(Rpwd[i])) return true;
if(true)
break;
else
cout << "Should contain upper case";
}
}
}
int main() {
string Lusr, Lpwd, Rusr, Rpwd, name, pwd;
while(1) {
cout << "___________________________________" << endl;
cout << "Chose 1 to Register or 2 to Login" << endl;
cout << "___________________________________" << endl;
cout << "1.Register" << endl;
cout << "2.Login" << endl;
cout << "3.Exit" << endl;
cout << "___________________________________" << endl;
int choice;
cin >> choice;
if(choice == 1) // register
{
ofstream of("register.txt");
if(!of.is_open()) {
cout << "file not exist" << endl;
}
do {
cout << "Username should contain capital,small letters and "
"numbers. "
<< endl;
cout << "______________________________________" << endl;
cout << "Enter new username:" << endl;
cin.ignore();
getline(cin, Rusr);
isvalidName(Rusr);
} while(isvalidName(Rusr) == true);
do {
cout << "Password should contain capital,small letters,special "
"characters and numbers. "
<< endl;
cout << "_______________________________________" << endl;
cout << "Enter new passsword:" << endl;
getline(cin, Rpwd);
isvalidPwd(Rpwd);
} while(isvalidPwd(Rpwd) == true);
of << Rusr;
of << '\n';
of << Rpwd;
of.close();
}
else if(choice == 2) {
ifstream f("register.txt");
if(!f.is_open()) {
cout << "file not open" << endl;
}
getline(f, name, '\n');
getline(f, pwd, '\n');
f.close();
cout << "Enter username:" << endl;
cin.ignore();
getline(cin, Lusr);
cout << "Enter passsword:" << endl;
getline(cin, Lpwd);
if(Lpwd == pwd && Lusr == name) {
cout << "Welcome " << Lusr << endl;
;
break;
}
cout << "Wrong name and password" << endl;
}
else if(choice == 3) {
return 1;
} else {
cout << "Invalid input!Try again." << endl;
}
}
return 0;
}
With your code, some of your logic is wrong. When you say this
if(Rusr.length() > 5 && Rusr.length() < 20) // length constraint
return true;
else
cout << "Invalid username`enter code here`" << endl;
Any string that is between 5 and 20 characters will be accepted as a valid username. To fix this, you need to go through all your requirements, then return true. If any of the requirements fail, return false. This makes it so that the only way that the username will be valid is if it has already passed all the requirements.
bool isvalidName(string Rusr)
{
if(Rusr.length() < 5 || Rusr.length() > 20) // length constraint
{
std::cout << "invalid username length" << std::endl;
return false;
}
for(int i = 0; i < Rusr.length(); i++) // check if digits are present
{
if(isdigit(Rusr[i])) // if a digit is present, continue
{
break;
}
if(i == Rusr.length() - 1) // No digits were found
{
return false;
}
}
for(int i = 0; i < Rusr.length(); i++) // check for lowercase
{
if(islower(Rusr[i])) {
break;
}
if(i == Rusr.length() - 1) // No lowercase letters were found
{
cout << "Invalid username";
return false;
}
}
for(int i = 0; i < Rusr.length(); i++) // check for uppercase
{
if(isupper(Rusr[i]))
{
break;
}
if(i == Rusr.length() - 1) // No uppercase letters were found
{
cout << "Invalid username";
return false;
}
}
return true;
}
This way, the only way you return true is if it gets past all the constraints.
For the password, you would want to follow this model and adjust for those constraints.
Some other things to watch out for are the extra braces you have included. Best practice is to not change the scope further in than you need to, so you should avoid the braces in almost every case.
Both your functions fail to return the value you've declared that they should return in all branches, so your program has undefined behavior.
Also, the logic is flawed. Example:
bool isvalidName(string Rusr) {
if(Rusr.length() > 5 && Rusr.length() < 20) // length constraint
return true;
else
cout << "Invalid username`enter code here`" << endl;
// .. the rest ...
}
Here you check that the length is [6, 19] characters long - and return true; - that's all it takes to get Rusr approved. None of the other tests in your function will be executed if the name has an approved length.
Your code is riddled with similar mistakes.
for(int i = 0; i < Rusr.length(); i++) // check if digits are present
{
if(isdigit(Rusr[i]) == true) return true;
The first digit you encounter makes isvalidName return true - so now you have a name with an invalid length that contains a digit - approved!
Similar issue below. A name with an illegal length, without digits, that contains a lowercase letter is immediately approved:
for(int i = 0; i < Rusr.length(); i++) // check for lowercase
{
if(islower(Rusr[i])) {
return true;
And finally, if a name with an illegal length, without digits and without lowercase letters contains an uppercase letter, it's approved:
for(int i = 0; i < Rusr.length(); i++) // check for uppercase
{
if(isupper(Rusr[i])) return true;
If none of the above applies - you don't return anything (causing undefined behavior).
Your second function follows this pattern.
Ok so, this is gonna be a long one...
Explanation of what the project is supposed to do:
My final project is a bank teller system that stores all the account related data on a text files.
The file in question, "accounts.txt", is where all the account data is stored. It is read and write, and behaves strangely when an ofstream is introduced...
The "accounts.txt" file is formated as follows
01481
554-00-8336
Jane Jones
1483 N. RealmSecond Ave., Burlington, VT 05401
564 425 5052
02650
727-22-1072
Jennifer Armstrong
1450 W. Main Rd., Burlington, VT 05401
202 545 5485
it continues repeating the same ordered sets of information...
One of the core parts of the program relies on reading these values into 5 separate arrays, each pertaining to type of data (name, address, etc).
I am going to dump the entire program because I think it might be necessary to fix the problem, just understand that the main function in question is addAccount() and is located at the bottom.
Note that the purpose of this function is to read the entire accounts.txt file line by line into memory, determine at what point the arrays used to store the file are being filled with empty data (we were told by the course instructor to make the array size 100, meaning that most of the data read into the array is empty space) get the desired account information from the user, update the file in memory, and rewrite the file...
also note that the file format was predetermined by the course instructor
The code:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
const int TELLERS_SIZE = 5;
const int ACCOUNTS_SIZE = 100;
const string TELLERS_FILE = "tellers.txt";
const string ACCOUNTS_FILE = "accounts.txt";
int beginMenu();
bool login(string fileName);
int baseMenu();
void searchAccount(string fileName);
void addAccount(string fileName);
int main() {
int beginSelection;
do {
beginSelection = beginMenu();
if (beginSelection == 2) {
return 0;
}
bool loginIsTrue = login(TELLERS_FILE);
while (loginIsTrue) {
int baseSelection = baseMenu();
if (baseSelection == 1) {
addAccount(ACCOUNTS_FILE);
}
if (baseSelection == 4) {
searchAccount(ACCOUNTS_FILE);
}
if (baseSelection == 8) {
loginIsTrue = false;
}
}
} while (beginSelection == 1);
}
// Print the fisrt menu and return selection
int beginMenu() {
// Establish return value and validation
int menuSelection;
string userInput;
bool menuSelectionIsValid = false;
// Print options
do {
cout << "\n";
cout << "[1] Login" << "\n";
cout << "[2] Quit" << "\n";
cout << "Please enter a selection";
cout << "\n";
getline(cin, userInput);
// Validate input
if (userInput == "1") {
menuSelectionIsValid = true;
menuSelection = 1;
}
else if (userInput == "2") {
menuSelectionIsValid = true;
menuSelection = 2;
}
else {
cout << "Invalid input!" << "\n";
}
} while (!menuSelectionIsValid);
return menuSelection;
}
// Perform login and return true or false
bool login(string fileName) {
// Establish variables
string username[TELLERS_SIZE];
string password[TELLERS_SIZE];
string usernameInput;
string passwordInput;
bool loginIsValid = false;
// Establish fin
ifstream fin(fileName);
if (!fin.is_open()) {
cout << "File cannot be opened " << fileName << "\n";
return false;
}
// Read tellers.dat
for (int i = 0; i < TELLERS_SIZE; i++) {
fin >> username[i];
fin >> password[i];
}
// Read user input
cout << "\n";
cout << "Username: ";
getline(cin, usernameInput);
cout << "Password: ";
getline(cin, passwordInput);
// Verify login information
for (int i = 0; i < TELLERS_SIZE; i++) {
if (username[i] == usernameInput && password[i] == passwordInput) {
cout << "Login succesful" << "\n";
loginIsValid = true;
return true;
}
}
// Inform user of error
cout << "Invalid username or password!" << "\n";
return false;
}
// Print base functions menu and return selection
int baseMenu () {
// Establish return value and validation
int menuSelection;
string userInput;
bool menuSelectionIsValid = false;
do {
// Print options
cout << "\n";
cout << "[1] Add Account" << "\n";
cout << "[2] Remove Account" << "\n";
cout << "[3] Update Account" << "\n";
cout << "[4] Search Account" << "\n";
cout << "[5] Make A Deposit" << "\n";
cout << "[6] Make A Withdrawal" << "\n";
cout << "[7] Check Balance" << "\n";
cout << "[8] Logout" << "\n";
cout << "Please enter a selection";
cout << "\n";
getline(cin, userInput);
// Validate input
if (userInput == "1") {
menuSelectionIsValid = true;
menuSelection = 1;
}
else if (userInput == "2") {
menuSelectionIsValid = true;
menuSelection = 2;
}
else if (userInput == "3") {
menuSelectionIsValid = true;
menuSelection = 3;
}
else if (userInput == "4") {
menuSelectionIsValid = true;
menuSelection = 4;
}
else if (userInput == "5") {
menuSelectionIsValid = true;
menuSelection = 5;
}
else if (userInput == "6") {
menuSelectionIsValid = true;
menuSelection = 6;
}
else if (userInput == "7") {
menuSelectionIsValid = true;
menuSelection = 7;
}
else if (userInput == "8") {
menuSelectionIsValid = true;
menuSelection = 8;
}
else {
cout << "Invalid input!" << "\n";
}
} while (!menuSelectionIsValid);
return menuSelection;
}
// Locate account and print relevant information
void searchAccount(string fileName) {
// Establish arrays
string accountNumber[ACCOUNTS_SIZE];
string accountSSN[ACCOUNTS_SIZE];
string accountName[ACCOUNTS_SIZE];
string accountAddress[ACCOUNTS_SIZE];
string accountPhone[ACCOUNTS_SIZE];
// Establish validation variables
string userInput;
bool accountFound = false;
// Establish and validate fin
ifstream fin(fileName);
if (!fin.is_open()) {
cout << "File cannot be opened " << fileName << "\n";
}
// Get desired account number
cout << "\n";
cout << "Account number: ";
getline(cin, userInput);
// Read information from file
for (int i = 0; i < ACCOUNTS_SIZE; i++) {
getline(fin, accountNumber[i]);
getline(fin, accountSSN[i]);
getline(fin, accountName[i]);
getline(fin, accountAddress[i]);
getline(fin, accountPhone[i]);
}
// Search for account
for (int i = 0; i < ACCOUNTS_SIZE; i++) {
if (accountNumber[i] == userInput && userInput != "") {
accountFound = true;
}
// Display account information
if (accountFound == true) {
cout << "Account Found" << "\n";
cout << "Displaying account information" << "\n" << "\n";
cout << accountNumber[i] << "\n";
cout << accountSSN[i] << "\n";
cout << accountName[i] << "\n";
cout << accountAddress[i] << "\n";
cout << accountPhone[i] << "\n";
break;
}
}
// Inform user that account doesnt exist
if (accountFound == false) {
cout << "Unable to find account: " << userInput << "\n";
}
}
void addAccount(string fileName) {
string accountNumber[ACCOUNTS_SIZE];
string accountSSN[ACCOUNTS_SIZE];
string accountName[ACCOUNTS_SIZE];
string accountAddress[ACCOUNTS_SIZE];
string accountPhone[ACCOUNTS_SIZE];
ifstream fin(fileName);
// ofstream fout(fileName);
string userAccountNumber;
string userAccountSSN;
string userAccountName;
string userAccountAddress;
string userAccountPhone;
bool accountNumberIsTaken = true;
for (int i = 0; i < ACCOUNTS_SIZE; i++) {
getline(fin, accountNumber[i]);
getline(fin, accountSSN[i]);
getline(fin, accountName[i]);
getline(fin, accountAddress[i]);
getline(fin, accountPhone[i]);
}
do {
accountNumberIsTaken = false;
cout << "\n";
cout << "Enter desired account number: ";
getline(cin, userAccountNumber);
for (int i = 0; i < ACCOUNTS_SIZE; i++) {
if (userAccountNumber == accountNumber[i] || userAccountNumber == "") {
cout << "That account number is already in use" << "\n";
accountNumberIsTaken = true;
break;
}
}
} while (accountNumberIsTaken);
/*
cout << "Enter SSN: ";
getline(cin, userAccountSSN);
cout << "Enter full name: ";
getline(cin, userAccountName);
cout << "Enter address: ";
getline(cin, userAccountAddress);
cout << "Enter phone number: ";
getline(cin, userAccountPhone);
for (int i = 0; i < ACCOUNTS_SIZE; i++) {
if (accountNumber[i] == "") {
cout << "empty space found at" << i;
accountNumber[i] = userAccountNumber;
accountSSN[i] = userAccountSSN;
accountName[i] = userAccountName;
accountAddress[i] = userAccountAddress;
accountPhone[i] = userAccountPhone;
break;
}
}
for (int i = 0; i < ACCOUNTS_SIZE; i++) {
fout << accountNumber[i] << "\n";
fout << accountSSN[i] << "\n";
fout << accountName[i] << "\n";
fout << accountAddress[i] << "\n";
fout << accountPhone[i] << "\n";
}
*/
}
The issue:
The base code, without anything commented out, does not work at all.
Both the accountSearch() and addAccount() functions which rely on reading "accounts.txt" will report that an account number clearly present on "accounts.dat" is not present.
After commenting out ofstream fout(fileName); and the lower part of the addAccount() that relies on writing to the file AND making a slight change to the "accounts.txt" file and saving changes, things start working again
This project is being written in Visual Studio 2019.
Apologies if this is a poor explanation. Please ask for clarification if necessary.
You can't have filename opened as both an ifstream and an ofstream at the same time! So, move your declaration/constructor for fout to after the code for reading fin, like this:
void addAccount(string fileName) {
string accountNumber[ACCOUNTS_SIZE];
string accountSSN[ACCOUNTS_SIZE];
string accountName[ACCOUNTS_SIZE];
string accountAddress[ACCOUNTS_SIZE];
string accountPhone[ACCOUNTS_SIZE];
ifstream fin(fileName);
// ofstream fout(fileName); /// CANNOT BE HERE!
string userAccountNumber;
///... Here, have all your reading and input code (as it is) …
///...
///... Finished reading, etc., so CLOSE "fin" then get the "fout" …
fin.close();
ofstream fout(fileName); // NOW we can create the output stream!
///... and use your existing code to do the writing
for (int i = 0; i < ACCOUNTS_SIZE; i++) {
fout << accountNumber[i] << "\n";
fout << accountSSN[i] << "\n";
fout << accountName[i] << "\n";
fout << accountAddress[i] << "\n";
fout << accountPhone[i] << "\n";
}
fout.close(); /// When finished, CLOSE the file!
}
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
here is my main . I get the error for the part I am checking whether the game had a winner or not. the errors are referring to the if parts where i wanna check the returned data from chkwin method
#include<iostream>
#include<string>
#include "TicTacToe.h"
using namespace std;
int main()
{
string choice = "";
string name1 = "";
string name2 = "";
string change = "";
int choice_num;
TicTacToe game;
cout << "Welcome to TicTacToe World!\n"
<< "In order to Start Please Enter the name of the first player\n\n";
getline(cin, name1);
cout << "\nGreat, Now Please Enter the name of the second player\n\n";
getline(cin,
name2);
cout << "\nAwesome Let's Get Started!\n";
do
{
cout << "\nPlease choose what do you want to do by entering the number of your choice\n"
<< "1.Start the game.\n"
<< "2.Change the names.\n"
<< "3.View Scores\n"
<< "4.Exit the Game :(\n\n";
getline(cin, choice);
if (choice == "1")
{
for (int i = 1; 1 <= 9; i++)
{
if (i % 2 != 0)
{
cout << "It's " << name1 << " Turn. Please Make Your move.";
cin >> choice_num;
cin.ignore();
game.setMove(choice_num, 1);
if (game.chkWin == 1)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == -1)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == 0)
{
cout <<"The Game is a Draw! ";
}
}
else
{
cout << "It's " << name1 << " Turn. Please Make Your move.";
cin >> choice;
cin.ignore();
game.setMove(choice_num, 2);
if ( 1 == game.chkWin)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == -1)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == 0)
{
cout << "The Game is a Draw! ";
}
}
}
}
else if (choice == "2")
{
do
{
cout << "\nwhich player do you want its name to be changed? (Enter 1 for the first, 2 for the second and 3 for both)\n";
getline(cin, change);
if (change == "1")
{
cout << "\nPlease Enter the new name for the player one.\n";
getline(cin, name1);
}
else if (change == "2")
{
cout << "\nPlease Enter the new name for the player two.\n";
getline(cin, name2);
}
else if (change == "3")
{
cout << "\nPlease Enter the new name for the player one.\n";
getline(cin, name1);
cout << "\nPlease Enter the new name for the player two.\n";
getline(cin, name2);
}
else
{
cout << "\nPlease Enter a Valid Choice.\n";
}
} while (change != "1" && change != "2" && change != "3");
}
else if (choice == "3")
{
cout << "\n" << game.getResults(name1, name2);
}
else if (choice != "4")
{
cout << "\nPlease Enter a Correct number\n";
}
} while (choice!= "4");
cout << "\nFinal Results are: \n\n"
<< game.getResults(name1, name2);
cout << "\nThank you for using our program. Hope to see You Again. Bye Bye!!\n";
system("Pause");
return 0;
}
my class
#include<iostream>
#include<string>
using namespace std;
#ifndef TICTACTOE_H
#define TICTACTOE_H
class TicTacToe
{
private:
const static int SIZE = 3;
int table[SIZE][SIZE];
int results[SIZE];
int winner = 2;
public:
TicTacToe();
void setMove(int , int );
int chkWin();
string getResults(string , string );
};
#endif
here is my methods declaration:
#include<iostream>
#include<string>
#include "TicTacToe.h"
using namespace std;
TicTacToe::TicTacToe()
{
for (int i = 0; i < SIZE; i++)
{
results[i] = 0;
for (int j = 0; j < SIZE; j++)
{
table[i][j] = 0;
}
}
}
void TicTacToe::setMove(int place, int player)
{
int field = place;
if (field == 1)
{
if (table[0][0] == 0)
{
table[0][0] = player;
}
else
{
cout << "\nYou cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 2)
{
if (table[0][1] == 0)
{
table[0][1] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 3)
{
if (table[0][2] == 0)
{
table[0][2] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 4)
{
if (table[1][0] == 0)
{
table[1][0] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 5)
{
if (table[1][1] == 0)
{
table[1][1] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 6)
{
if (table[1][2] == 0)
{
table[1][2] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 7)
{
if (table[2][0] == 0)
{
table[2][0] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 8)
{
if (table[2][1] == 0)
{
table[2][1] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
else if (field == 9)
{
if (table[2][2] == 0)
{
table[2][2] = player;
}
else
{
cout << "You cannot make this move this place is already occupied.Please choose another Field\n";
cin >> field;
cin.ignore();
setMove(field, player);
}
}
}
int TicTacToe::chkWin()
{
for (int i = 0; i < SIZE; i++)
{
if (table[i][0] == table[i][1] && table[i][0] == table[i][2])
{
if (table[i][0] == 1)
{
results[0] += 1;
winner = 1;
}
else if (table[i][0] == 2)
{
results[2] += 1;
winner = -1;
}
}
else if (table[0][i] == table[1][i] && table[0][i] == table[2][i])
{
if (table[0][i] == 1)
{
results[0] += 1;
winner = 1;
}
else if (table[0][i] == 2)
{
results[2] += 1;
winner = -1;
}
}
}
if ((table[0][0] == table[1][1] && table[0][0] == table[2][2]) || (table[0][2] == table[1][1] && table[0][2] == table[2][0]))
{
if (table[1][1] == 1)
{
results[0] += 1;
winner = 1;
}
else if (table[1][1] == 2)
{
results[2] += 1;
winner = -1;
}
}
else
{
for (int i = 0; i < SIZE; i++)
{
for (int j = 0; j < SIZE; j++)
{
if(table[i][j] == 0)
{
winner = 2;
}
}
}
results[1] += 1;;
return winner;
}
}
string TicTacToe::getResults(string name1, string name2)
{
return ( name1 + " : " + to_string(results[0]) + "\n"
+ "Draws : " + to_string(results[1]) + "\n"
+ name2 + " : " + to_string(results[2]) + "\n");
}
Compareing functions with integers doesn't make sense. You have to use () operator to call functions like this:
if (game.chkWin() == 1)
instead of
if (game.chkWin == 1)
Poor:
game.setMove(choice_num, 1);
if (game.chkWin == 1)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == -1)
{
cout << name1 << " has won this Game!";
}
else if (game.chkWin == 0)
{
cout <<"The Game is a Draw! ";
}
Better:
game.setMove(choice_num, 1);
switch (game.chkWin()) {
case 1:
cout << name1 << " has won this Game!";
break;
case -1:
cout << name1 << " has won this Game!";
break;
case 0:
cout <<"The Game is a Draw! ";
break;
}
The basic problem is using "==" with function game.chkWin, instead of with the result of function game.chkWin().
But in cases like this (pun intended) a "switch()" block is probably more readable and better style than multiple "if/else" statements.
'Hope that helps...
I Updated the code with the suggestions you gave me! Now i dont know how the heck to call the displayinfo function in main? it says too few arguments passed yet why should i pass arguments when I have another function passing arguments with all the data! I dont know how to call on displayinfo to display displayinfos contents
#include<iostream>
#include<array>
#include<iomanip>
#include<string>
using namespace std;
void setCourseName(string);
void InputValue();
int main()
{
InputValue();
displayinfo( d, b);
}
void displayinfo(int d, array<char, 7> b)
{
for (int k = 0; k < d; k++)
{
cout << "Semester: " << b[k] << endl;
}
}
void InputValue()
{
char semester;
string courseTitle;
string courseType;
int credits;
string lettergrade;
double gpa;
array<char, 7> sem1array;
array<string, 7> sem1coursetitles;
array<string, 7> sem1courseTypes;
array<int, 7> sem1credits;
array<string, 7> sem1lettergrades;
int amountOFgrades = 0;
cout << "How many grades are going to be entered today? min 1 - max 7" << endl;
cin >> amountOFgrades;
for (int counter = 0; counter < amountOFgrades; counter++)
{
bool valid1 = false;
bool validCredits = false;
bool valid3 = false;
bool valid4 = false;
while (valid1 == false)
{
cout << "Enter Semester Number" << endl;
cin >> semester;
if (semester == '1' || semester == '2')
{
cout << "valid input" << endl;
sem1array[counter] = semester;
valid1 = true;
}
else
{
cout << "Invalid Input! RE ENTER SEMESTER NUMBER EITHER 1 OR 2!" << endl;
}
}
cout << "Enter Course Title: " << endl;
cin.ignore();
getline(cin, courseTitle);
if(courseTitle.size() <= 25)
sem1coursetitles[counter] = courseTitle;
else
{
cout << "Course Name Cannot Be More Than 25 Characters; Course name limited to first 25 characters!" << endl;
courseTitle = courseTitle.substr(0, 25);
sem1coursetitles[counter] = courseTitle;
}
while (valid3 == false)
{
cout << "Enter Course Type: Regular, AP, or Honors" << endl;
getline(cin, courseType);
if (courseType == "Regular" || courseType == "AP" || courseType == "Honors")
{
sem1courseTypes[counter] = courseType;
valid3 = true;
}
else
{
cout << "Invalid Input! RE ENTER COURSE TYPE EXACTLY HOW IT APPEARS EITHER Regular, AP, or Honors!" << endl;
}
}
while(validCredits == false)
{
cout << "Enter Credits Earned For Course: **Can Either Be 1-4 Credits**" << endl;
cin >> credits;
if (credits == 1 || credits == 2 || credits == 3 || credits == 4)
{
sem1credits[counter] = credits;
validCredits = true;
}
else
{
cout << "Invalid Output! Must Enter Number 1-4 For Credits Earned!" << endl;
}
}
while (valid4 == false)
{
cout << "Enter Letter Grade; Capital Letter Followed By A Plus + or Minus - If There Is One!Example: A+, A-, A, B+..." << endl;
cin.ignore();
getline(cin, lettergrade);
if (lettergrade == "A+")
{
gpa = 4.0;
sem1lettergrades[counter] = lettergrade;
valid4 = true;
}
else if (lettergrade == "A")
{
gpa = 4.0;
sem1lettergrades[counter] = lettergrade;
valid4 = true;
}
else if (lettergrade == "A-")
{
gpa = 3.7;
sem1lettergrades[counter] = lettergrade;
valid4 = true;
}
else if (lettergrade == "B+")
{
gpa = 3.3;
sem1lettergrades[counter] = lettergrade;
valid4 = true;
}
else if (lettergrade == "B")
{
gpa = 3.0;
sem1lettergrades[counter] = lettergrade;
valid4 = true;
}
else if (lettergrade == "B-")
{
gpa = 2.7;
sem1lettergrades[counter] = lettergrade;
valid4 = true;
}
else if (lettergrade == "C+")
{
gpa = 2.3;
sem1lettergrades[counter] = lettergrade;
valid4 = true;
}
else if (lettergrade == "C")
{
gpa = 2.0;
sem1lettergrades[counter] = lettergrade;
valid4 = true;
}
else if (lettergrade == "C-")
{
gpa = 1.7;
sem1lettergrades[counter] = lettergrade;
valid4 = true;
}
else if (lettergrade == "D+")
{
gpa = 1.3;
sem1lettergrades[counter] = lettergrade;
valid4 = true;
}
else if (lettergrade == "D")
{
gpa = 1.0;
sem1lettergrades[counter] = lettergrade;
valid4 = true;
}
else if (lettergrade == "F")
{
gpa = 0.0;
sem1lettergrades[counter] = lettergrade;
valid4 = true;
}
else
{
cout << "Invalid Input! Please Re-Enter Letter Grade! Example: A+, A-, A, B+..." << endl;
}
}
}
displayinfo(amountOFgrades, sem1array);
}
Return and passing arrays is very straight forward. Here is a very simplified version.
#include <array>
#include <iostream>
std::array<int, 7> input_value()
{
std::array<int, 7> data;
// fill array
return data;
}
void display_array(std::array<int,7> data)
{
for (int x : data)
std::cout << x << ' ';
std::cout << '\n';
}
int main()
{
std::array<int,7> data = input_value();
display_array(data);
}
You can improve this by multiple things. Changing display_array to take a const reference instead would be easiest. Make it more general by using templates (or spans). But make sure you understand the differences and learn.
You declare displayinfo after the function using it, which means the functions won't find it.
You should either put the code of "displayinfo" before or declare its head at the beginning of your file (which I'd recommand). I would recommand to do the same with InputValue :
void InputValue();
void displayinfo(char b[]);
Now there are many problems in your function :
/*you're using two parameters of type : array<char,7> and array<string,7>*/
void displayinfo(char b[])
{
for (int k = 0; k < sem1array/*supposed to "b"*/.size(); k++)
{
/*once again you called "sem1array" "b" in this scope*/
/*"sem1coursetitles" should be the second paramater*/
cout << "Semester: " << sem1array[k] << " " << "Course: " << sem1coursetitles[k] << endl;
}
}
That would lead me to change your function to :
void displayinfo(array<char,7> b, array<string,7> c)
{
for (int k = 0; k < b.size(); k++)
{
cout << "Semester: " << b[k] << "\tCourse: " << c[k] << endl;
}
}
So I'd change the call to this function to :
displayinfo(sem1array,sem1coursetitles);
Concerning the call in your main, you're not giving any parameter to your function, so it cannot work.