I am getting errors in my C++ program - c++

I am current creating a weather application that is giving me an error. It said there is something wrong with != but I am not sure what is wrong so can anyone help. It is giving me the error operand types are incompatible ("std::string *" and "const char *")(there is 4) and '!=': no conversion from 'const char *' to 'std::string *'
Thank you
C++ code:
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void moveTemperaturesToRight(double temperatures[], double windSpeed[], string windDirection[])
{
for (int i = 3; i > 0; i--)
{
temperatures[i] = temperatures[i - 1];
windSpeed[i] = windSpeed[i - 1];
windDirection[i] = windDirection[i - 1];
}
}
int main()
{
string name;
int choice;
int numOfReadings = 0;
double temperatures[4], windSpeeds[4];
string windDirections[4];
bool initialized = false;
string str;
//Have the user provide a name for the weather station upon entry.
cout << "Enter the name of weather station: ";
getline(cin, name);
//Control loop to perform various actions.
while (true)
{
cout << "1. Input a complete weather reading." << endl;
cout << "2. Print the current weather." << endl;
cout << "3. Print the weather history (from most recent to oldest)." << endl;
cout << "4. Exit the program." << endl;
cout << "Enter your choice: ";
cin >> str;
if (str.length() != 1 || str < "1" || str > "4")
choice = 0;
else
choice = atoi(str.c_str());
//Switch based on choice.
switch (choice)
{
case 1: moveTemperaturesToRight(temperatures, windSpeeds, windDirections);
do {
cout << "Enter the temperature (a value >=0):";
cin >> temperatures[0];
} while (temperatures < 0);
//get correct wind speed
do
{
cout << "Enter the wind speed (a value >=0):";
cin >> windSpeeds[0];
} while (windSpeeds < 0);
//get correct wind direction
do
{
cout << "Enter the wind direction (North,South,East or West):";
cin >> windDirections[0];
} while (windDirections != "North" && windDirections != "South" && windDirections != "East" && windDirections != "West");
initialized = true;
if(initialized)
numOfReadings++;
if (numOfReadings > 4)
numOfReadings = 4;
break;
case 3: //Print the current weather, if valid weather is entered.
for (int i = 0; i < numOfReadings; i++)
{
cout << "*****" << name << "*****" << endl;
cout << "Temperature: " << temperatures[i] << endl;
cout << "Wind speed: " << windSpeeds[i] << endl;
cout << "Wind direction: " << windDirections[i] << endl << endl;
}
if (numOfReadings == 0)
cout << "Please enter the details before asking to print." << endl;
break;
case 2: if (numOfReadings == 0)
{
cout << "Please enter the details before asking to print." << endl;
break;
}
cout << "*****" << name << "*****" << endl;
cout << "Temperature: " << temperatures[0] << endl;
cout << "Wind speed: " << windSpeeds[0] << endl;
cout << "Wind direction: " << windDirections[0] << endl << endl;
break;
case 4: return 0; //Stops execution.
default: cout << "Invalid choice. Please follow the menu." << endl;
}
}
}

You need to compare an element of windDirections with the literal.
Did you mean windDirections[0] != "North" &c.?
Currently you're attempting to compare an array of std::strings, and so the compiler issues a diagnostic. It does its best in decaying the array to a pointer to std::string (hence the specific error), but then gives up.

Related

Trying to incorporate void functions into switch statements

I'm a novice coding student and trying to create a menu using structs, functions, and switch statements to make a mini database for a class assignment. I'm trying to implant the functions into the switch statements.
I'm getting errors on lines 87 and 137 and I'm not sure where I'm going wrong. Any help, explanation, or correction is much appreciated.
#include <iostream>
#include <string>
#include <iomanip>
#include <sstream>
using namespace std;
// Jaret Clark
// Week 3 Interactive Assignment
// INT 499
// Prof. Joseph Issa
// 03/31/2022
struct EZTechMovie {
string name;
string *cast[10];
string rating;
};
void displaymovie(EZTechMovie movie, int cast_num) {
int i;
cout << endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
cout << endl;
cout << "Your entry:\n";
//Movies
cout << endl;
cout << "Movie TITLE: " << movie.name;
cout << endl;
//Movie rating
cout << "Movie Rating: " << movie.rating;
cout << endl;
//Cast name
cout << "Main Cast Members: \n";
//loop for cast members ~ stores in array
for (int i = 0; i < cast_num; ++i) {
cout << movie.cast[i];
cout << endl;
}
}
void mainmenu() {
string movie_input;
int m;
cout << endl;
cout << "Would you like to store movies into database? (yes or no) ";
getline(cin, movie_input);
cout << endl;
if (movie_input == "yes") {
string cont;
string cast_name;
int x, m, n, i, cast_num;
EZTechMovie moviedb[100];
cout << endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
cout << endl;
for (n = 0; n < 100; n++) {
cout << "Movie Title: ";
getline(cin, moviedb[n].name);
cout << endl;
cout << "Movie rating: ";
getline(cin, moviedb[n].rating);
cout << endl;
cout << "How many cast do you want to enter? ";
cin >> cast_num;
cout << endl;
cin.ignore();
for (i = 0; i < cast_num; i++) {
cout << "Cast name: First and Last name: ";
getline(cin, moviedb[n].cast[i]);
cout << endl;
}
cout << endl;
displaymovie(moviedb[n], cast_num);
cout << endl;
cout << "Add more movies? (yes or no) ";
getline(cin, cont);
if (cont == "no") {
break;
}
cout << endl;
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" << endl;
cout << endl;
}
}
else if (movie_input == "no") {
return;
}
else {
cout << "INVALID Input";
mainmenu();
}
}
// menu
void movieMenu() {
int choice;
EZTechMovie movie;
do {
cout << "***********************Welcome to EZTechMovie Movie Entry Menu***********************" << endl;
cout << "Press 1 to Enter Movie Info - Name, Cast Members, and Rating.\n";
cout << "Press 2 to Retrieve movie info recently entered.\n";
cout << "Press 3 To Quit program.\n";
// evaluate menu options in switch case
switch (choice) {
case 1:
mainmenu();
break;
case 2:
displaymovie(EZTechMovie movie, int cast_num);
break;
case 3:
cout << "Thank you and Goodbye!";
break;
default:
cout: "Invalid Selection. Try again!\n";
}
//get menu selection
cin >> choice;
} while (choice != 3);
}
int main() {
movieMenu();
}
Regarding the error on line 87 (getline(cin, moviedb[n].cast[i]);) :
moviedb[n].cast[i] is a std::string*, not std::string like you might have meant.
A quick compilation fix would be to use:
getline(cin, *(moviedb[n].cast[i]));
i.e. dereference the pointer.
However - this code raises other design/programming issues:
Why do you use std::string* and not std::string in the first place.
Why do you use C style array instead of std::vector (or std::array if you can commit to the size). This is relevant for both: string *cast[10]; and EZTechMovie moviedb[100];

while loop if and else

What the code does is ask the user which card he wants and prints out a statement depending on which card is chosen.
My aim is to loop back to the card select function if numbers other than 1,2 and 3 are entered.
There is also a for loop which allows this process to go around multiple times.
What is the best way and how can I do this?
int CardSelect() {
cout << "Enter 1 for hearts" << endl;
cout << " " << endl;
cout << "Enter 2 for diamonds" << endl;
cout << " " << endl;
cout << "Enter 3 for joker" << endl;
return 0;
};
int main() {
for (int i = 1; i <= 5; i++) {
CardSelect();
int cardchoice;
cin >> cardchoice;
cardchoice = CardSelect();
if (cardchoice == 1) {
cout << "You got hearts" << endl;
loop = false;
} else if (cardchoice == 2) {
cout << "You got diamonds" << endl;
loop = false;
} else if (cardchoice == 3) {
cout << "You got joker" << endl;
loop = false;
} else {
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
}
}
}
Change return type of CardSelect() to void, since your simply printing some statements in that function:
void CardSelect()
{ // Your cout statements
}
Call that in main(), and use a switch case for your cardchoice variable.
If you want to keep running the switch statement till you get a valid input, put everything in an inifinte loop (such as a while(1)) and set an exit condition by setting a boolean to true (set it to false initially) and using break when condition is satisified, to get out of the loop:
int main()
{
while(1)
{
bool valid = false;
CardSelect(); // call to your function
int cardchoice;
cin >> cardchoice;
switch(cardchoice)
{
case 1:
cout << "You got hearts" << endl;
valid = true;
break;
case 2:
cout << "You got diamonds" << endl;
valid = true;
break;
case 3:
cout << "You got joker" << endl;
valid = true;
break;
default:
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
break;
} if(valid) break;
}
}
you should not call cardchoice = CardSelect();.
This call is overwriting cardchoice with 0. Remove this call.
You print values to see what is happening. Its a good way of learning.
Hope this will help.
First, what you are looking for is continue, second you need to get rid of this line which makes no sense :
cardchoice = CardSelect();
as it erases user input
int CardSelect() {
cout << "Enter 1 for hearts" << endl;
cout << " " << endl;
cout << "Enter 2 for diamonds" << endl;
cout << " " << endl;
cout << "Enter 3 for joker" << endl;
return 0;
};
int main() {
for (int i = 1; i <= 5; i++) {
CardSelect();
int cardchoice;
cin >> cardchoice;
if (cardchoice == 1) {
cout << "You got hearts" << endl;
}
else if (cardchoice == 2) {
cout << "You got diamonds" << endl;
}
else if (cardchoice == 3) {
cout << "You got joker" << endl;
}
else {
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
}
}
}

Sporadic infinite loop during do-while c++

Sometimes when I run the program, it runs perfectly fine. Sometimes I get an infinite loop that just keeps displaying my first choice menu. I tried searching for the error and I couldn't figure it out. I thought there was an error in my input statement when I got the menuChoice, but I was unable to troubleshoot it out. Should I be checking the value of menuChoice more often? To better specify, I am referring to the second do-while loop, the one that reprints the menu choices after each iteration.
main.cpp
#include <vector>
#include <fstream>
#include <iostream>
#include "course.hpp"
using namespace std;
int main() {
int menuChoice, searchMenuChoice;
string fileName;
string line;
ifstream inStream;
string searchName;
string searchPrefix;
int searchNum;
vector<Course> courseList;
vector<int> enrolledClasses;
do{
cout << "Please enter the file that contains othe course data: ";
cin >> fileName;
inStream.open(fileName);
}while (!inStream.is_open());
cout << endl;
while (getline(inStream, line)){
courseList.push_back(Course(line));
}
cout << "Welcome to Banner NE, short for Never Existed!" << endl;
do {
cout << "\n"<< "---------------------------------------------" << endl;
cout << "1 - List all available classes" << endl;
cout << "2 - Search for a course" << endl;
cout << "3 - View your current enrolled courses" << endl;
cout << "4 - Enroll in course" << endl;
cout << "5 - Exit" << endl;
cout << "Make your selection here: ";
cin >> menuChoice;
cout << endl;
if (menuChoice == 5){
cout << "Thank you for using Banner NE and have a nice day!" << endl;
return 0;
}
if (menuChoice == 2) {
cout << endl;
cout << "Would you like to search by" << endl;
cout << "1 - Course number" << endl;
cout << "2 - Available seats remaining" << endl;
cout << "3 - Instructor name" << endl;
cout << "4 - Course prefix" << endl;
cout << "Make your selection: ";
cin >> searchMenuChoice;
if (searchMenuChoice == 2) {
for (int i = 0; i < courseList.size(); i++){
if (courseList.at(i).getSeatsRemaining() > 0)
courseList.at(i).printCourse();
}
}
if (searchMenuChoice == 1) {
cout << "Please enter the course number: ";
cin >> searchNum;
for (int i = 0; i < courseList.size(); i++){
if (courseList.at(i).MatchesCourseNumberSearch(searchNum))
courseList.at(i).printCourse();
break;
}
}
if (searchMenuChoice == 3) {
cout << "Please enter the name of the instructor: ";
cin >> searchName;
for (int i = 0; i < courseList.size(); i++) {
if (courseList.at(i).MatchesInstructorSearch(searchName))
courseList.at(i).printCourse();
}
}
if (searchMenuChoice == 4){
cout << "Please enter the prefix you would like to search for: ";
cin >> searchPrefix;
for (int x = 0; x < courseList.size(); x++)
if (courseList.at(x).MatchesPrefix(searchPrefix))
courseList.at(x).printCourse();
}
}
if (menuChoice == 1) {
for (int x = 0; x < courseList.size(); x++){
cout << "ID: " << x << "\t";
courseList.at(x).printCourse();
cout << endl;
}
}
if (menuChoice == 4) {
int classEnrollment;
cout << "Please enter the ID number of the class you would like to enroll: ";
cin >> classEnrollment;
if (courseList.at(classEnrollment).Enroll()){
enrolledClasses.push_back(classEnrollment);
cout << "You have enrolled in ID " << classEnrollment << endl;
}
else
cout << "There was not enough space, sorry." << endl;
}
if (menuChoice == 3){
for (int i = 0; i < enrolledClasses.size(); i++){
courseList.at(enrolledClasses.at(i)).printCourse();
cout << endl;
}
if (enrolledClasses.size() == 0 )
cout << "You are not currently enrolled in any classes." << endl;
}
} while (menuChoice != 5);
return 0;
}

Why is failed input validation returning me to the start of my program?

Really sorry if this is a dumb question. I know it must have a super easy solution but I've been staring at this for so long I can't see it. It doesn't help that I'm really new at this either.
Long story short for some reason entering an invalid input past the first time returns me back to my menu, and sometimes also asks me to enter weight immediately after instead of allowing me to enter a menu choice. It's just all around broken and I don't know why. Thanks.
#include <iostream>
#include <iomanip>
#include <limits>
using namespace std;
bool loopFlag = true;
bool loopFlagTwo = true;
int choice = 0;
int time = 0;
float weightPounds = 0;
float weight = 0;
const int BIKING = 8;
const int RUNNING = 10;
const int LIFTING = 3;
const float YOGA = 2.5;
int main()
{
cout << "Welcome to my Fitness Center" << endl;
do
{
cout << "\n\t____________________________________________________________" << endl;
cout << "\n\t\t\tMy Fitness Center" << endl;
cout << "\t\t\tActivity System" << endl;
cout << "\t____________________________________________________________" << endl;
cout << "\t\t\t Main Menu\n" << endl;
cout << "\t\t\t1) Stationary Bike" << endl;
cout << "\t\t\t2) Treadmill" << endl;
cout << "\t\t\t3) Weight Lifting" << endl;
cout << "\t\t\t4) Hatha Yoga" << endl;
cout << "\t\t\t5) End" << endl;
cout << "\t____________________________________________________________" << endl;
cout << "\n\nEnter the workout that you wish to track, or end to exit:" << endl;
do
{
cin >> choice;
if (cin.fail() || choice > 5 || choice < 1)
{
cout << "Invalid choice. Please choose from option 1 through 5." << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else if (choice == 5)
{
return 0;
}
else
{
loopFlag = false;
}
}
while (loopFlag);
do
{
cout << "\nPlease enter your weight in pounds: " << endl;
cin >> weightPounds;
if (cin.fail() || weightPounds <= 0)
{
cout << "Invalid weight entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
weight = weightPounds / 2.2;
cout << "\nYour weight is: \n" << fixed << setprecision(1) << weight << " kilograms." << endl;
if (choice == 1)
{
do
{
cout << "For how many minutes did you do this activity? " << endl;
cin >> time;
if (cin.fail() || time <= 0)
{
cout << "Invalid time entry!" << endl;
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
}
else
{
loopFlag = false;
}
}
while (loopFlag);
}
}
while (choice != 5);
return 0;
}
You need to set loopFlag to true before every do...while() you have, or use another flag, because after the first do...while(), loopFlag is always false.

C++ Address Book Array and Textfile

Sorry for the lack of previous explanation to my school's assignment. Here's what I'm working with and what I have / think I have to do.
I have the basic structure for populating the address book inside an array, however, the logic behind populating a text file is a bit beyond my knowledge. I've researched a few examples, however, the implementation is a bit tricky due to my novice programming ability.
I've gone through some code that looks relevant in regard to my requirements:
ifstream input("addressbook.txt");
ofstream out("addressbook.txt");
For ifstream, I believe implementing this into the voidAddBook::AddEntry() would work, though I've tried it and the code failed to compile, for multiple reasons.
For ostream, I'm lost and unsure as to how I can implement this correctly. I understand basic file input and output into a text file, however, this method is a bit more advanced and hence why I'm resorting to stackoverflow's guidance.
#include <iostream>
#include <string.h> //Required to use string compare
using namespace std;
class AddBook{
public:
AddBook()
{
count=0;
}
void AddEntry();
void DispAll();
void DispEntry(int i); // Displays one entry
void SearchLast();
int Menu();
struct EntryStruct
{
char FirstName[15];
char LastName[15];
char Birthday[15];
char PhoneNum[15];
char Email[15];
};
EntryStruct entries[100];
int count;
};
void AddBook::AddEntry()
{
cout << "Enter First Name: ";
cin >> entries[count].FirstName;
cout << "Enter Last Name: ";
cin >> entries[count].LastName;
cout << "Enter Date of Birth: ";
cin >> entries[count].Birthday;
cout << "Enter Phone Number: ";
cin >> entries[count].PhoneNum;
cout << "Enter Email: ";
cin >> entries[count].Email;
++count;
}
void AddBook::DispEntry(int i)
{
cout << "First name : " << entries[i].FirstName << endl;
cout << "Last name : " << entries[i].LastName << endl;
cout << "Date of birth : " << entries[i].Birthday << endl;
cout << "Phone number : " << entries[i].PhoneNum << endl;
cout << "Email: " << entries[i].Email << endl;
}
void AddBook::DispAll()
{
cout << "Number of entries : " << count << endl;
for(int i = 0;i < count;++i)
DispEntry(i);
}
void AddBook::SearchLast()
{
char lastname[32];
cout << "Enter last name : ";
cin >> lastname;
for(int i = 0;i < count;++i)
{
if(strcmp(lastname, entries[i].LastName) == 0)
{
cout << "Found ";
DispEntry(i);
cout << endl;
}
}
}
AddBook AddressBook;
int Menu()
{
int num;
bool BoolQuit = false;
while(BoolQuit == false)
{
cout << "Address Book Menu" << endl;
cout << "(1) Add A New Contact" << endl;
cout << "(2) Search By Last Name" << endl;
cout << "(3) Show Complete List" << endl;
cout << "(4) Exit And Save" << endl;
cout << endl;
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
return 0;
}
int main (){
Menu();
return 0;
}
As it currently stands, I'm still stuck. Here's where I believe I should start:
cout << "Please enter your selection (1-4) and press enter: ";
cin >> num;
cout << endl;
if (num == 1)
AddressBook.AddEntry();
else if (num == 2)
AddressBook.SearchLast();
else if (num == 3)
AddressBook.DispAll();
else if (num == 4)
BoolQuit = true;
//save first name
//save last name
//save dob
//save phone number
//save email
//exit
else
cout << "Please enter a number (1-4) and press enter: " << endl;
cout << endl;
}
Somehow, during menu option 4 the array should dump the data into a .txt file and arrange it in a way that it can be easily imported upon reloading the program. I'm a little confused as to how I can store the array data from each character array into a .txt file.
Well first, if the input is coming from the file input, then instead of doing cin >> x you would have to do input >> x. If it's coming from standard input (the keyboard), then you can use cin.
Also, your else if statement should be something like this:
while (true)
{
// ...
else if (num == 4)
{
for (int i = 0; i < AddressBook.count; ++i)
{
AddBook::EntryStruct data = AddressBook.entries[i];
out << data.FirstName << " " << data.LastName
<< std::endl
<< data.Birthday << std::endl
<< data.PhoneNum << std::endl
<< data.Email;
}
}
break;
}