Hi im having trouble with an if statement in C++. When I compile my code I get an error stating " no operator "||" matches these operands". Any guesses? The project is a small text based game I'm creating in visual studio.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <fstream>
using namespace std;
//Prototypes
void introScreen(int);
string characterCreation(string);
int choice;
string characterName, wepon1, wepon2, bow, sword, mace;
const string sword = sword;
const string bow = bow;
const string mace = mace;
// Functions
int main()
{
introScreen(choice);
return 0;
}
void introScreen(int choice)
{
cout << "----------------------------------------\n"
<< "Welcome to the arena!\n"
<< "Select a menu option\n"
<< "-----------------------------------------\n"
<< "1. New Game\n"
<< "2. Load\n"
<< "3. Exit\n\n"
<< "Enter your desired number ";
cin >> choice;
if (choice == 1)
characterCreation(characterName);
else
if (choice == 2)
exit(0);
else
if (choice == 3)
exit(1);
}
string characterCreation(string characterName,string wepon1,string wepon2, const string bow, const string sword, const string mace)
{
cout << "Welcome to the character creation menu!\n"
<< "Enter your name\n"
<< "Name: ";
cin.ignore();
getline(cin, characterName);
ofstream loadFile("Save.txt");
loadFile << characterName << endl;
cout << "\nEnter 2 wepons\n"
<< "Wepon list\n\n"
<< "Sword\n"
<< "Mace\n"
<< "Bow\n";
cin >> wepon1, wepon2;
if (wepon1 || wepon2 != bow || sword || mace)
{
cout << "\n\nThose wepons are invalid! Enter new ones\n";
cout << "\nEnter 2 wepons\n"
<< "Wepon list\n\n"
<< "sword\n"
<< "mace\n"
<< "bow\n";
cin >> wepon1, wepon2;
}
loadFile << wepon1 << endl
<< wepon2 << endl;
return characerName;
}
The '||' operator is an evaluation of a logical condition and you are asking it to evaluate a string type. Generally, when strings values are evaluated, they are evaluated as
if (weapon1 != "") then...
Also, be careful about how you set the value. String values are passed inside double quotation marks.
Related
#include <iostream>
#include <string>
#include <vector>
using namespace std;
//void FillNames(vector<string> & vecNames);
//void SortNames(vector<string> & vecNames);
int main() {
string firstName;
int i = 0;
cout << "Information:" << endl;
cout << "EOF character in windows is Control + Z" << endl;
cout << "and EOF character on Mac is Control + D:" << endl;
cout << "-----------------------------------------------" << endl;
while (i < 13) {
cout << "Enter first name only in all caps (example: JOHN)" << endl;
cout << "Enter EOF character to exit name entry: ";
cin >> firstName;
i++;
}
}
Here is a link to what i'm trying to accomplish.
https://drive.google.com/file/d/1AuW9hQPbd1f294dCZN6Q8Ac6lgIy0Ivf/view?usp=sharing
You can use the stream's input state to break the loop when EOF is entered:
while (i < 13) {
cout << "Enter first name only in all caps (example: JOHN)" << endl;
cout << "Enter EOF character to exit name entry: ";
if (cin >> firstName)
i++;
else
break;
}
Not under standing looping for arrays. Looping through all of grab some or search. Can someone explain the process? Thanks in advance. Sorry if duplicate. I looked around and couldnt find a solid explaination that I could understand.
#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
void allContacts(string names[], string phones[])
{
cout << "Showing all contacts... Press Q to go back to main menu" << endl;
}
void addName(string names[], string phones[])
{
bool keepGoing;
string input;
beginning:
for (int i = 0; i < sizeof(names); i++)
{
cout << "Enter contact name: ";
cin >> names[i];
cout << "Enter contact number: ";
cin >> phones[i];
cout << "Do you have another contact to add? y or no" << endl;
cin >> input;
if(input == "y" || input == "Y")
{
goto beginning;
}
if(input == "n" || input == "N")
{
cout << "Contacts you have entered: " << endl;
cout << names[i] << " : " << phones[i] << endl;
}
}
}
void searchName(string names[], string phones[])
{
string name;
cout << "Enter Name: ";
cin >> name;
cout << "Search for a name or Press Q to go back to main menu" << endl;
for (int i = 0; i < sizeof(names); i++){
if (name == names[i])
{
cout << counter << names[i] << " 's phone number is: " << phones[i] << endl;
} else {
cout << "No results found";
}
}
}
int main()
{
string names[100];
string phones[100];
int choice;
cout << "============================" << endl;
cout << "=== Welcome to PhoneBook ===" << endl;
cout << "============================" << endl;
cout << "1- Add a New Contact" << endl;
cout << "2- Search By Name" << endl;
cout << "3- Display All" << endl;
cout << "0- Exit" << endl;
cout << "Select a number: " << endl;
cin >> choice;
switch(choice)
{
case 1:
addName(names, phones);
break;
case 2:
searchName(names, phones);
break;
case 3:
allContacts(names, phones);
break;
case 0:
cout << "Exiting PhoneBook...";
break;
}
}
In C++ arrays lose attributes when passed to functions. Those attributes are capacity and size (number of filled slots). You will need to pass this additional information for each array:
void addName(string names[], unsigned int names_capacity, unsigned int names_size,
string phones[], unsigned int phones_capacity, unsigned int phones_size)
To get around this, you can use std::vector. The std::vector knows its capacity and size, so you don't have to pass additional attributes to your function.
Also, if you use tolower or toupper before you compare, you only need to make one comparison:
char input;
cout << "Do you have another contact to add? y or n" << endl;
cin >> input;
input = toupper(input);
if(input == 'Y')
When using strings, you can convert them to all uppercase or all lowercase by using std::transform, such as:
std::transform(input.begin(),
input.begin(), input.end(),
tolower);
I am currently taking a C++ programming class and am working on a project in which I have to create a fairly simple movie database. My code essentially works as intended yet in certain cases it causes the main menu to loop infinitely and I cannot figure out why. I brought this to my teacher and he cannot explain it either. He gave me a workaround but I would like to know if anyone can see the cause of the problem. Full code is as follows:
#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct MovieType
{
string title;
string director;
int year;
int length;
string rating;
};
MovieType addMovie() {
MovieType newMovie;
cout << "Movie title :";
getline(cin, newMovie.title);
cout << "Director :";
getline(cin, newMovie.director);
cout << "Year :";
cin >> newMovie.year;
cout << "Length(in minutes) :";
cin >> newMovie.length;
cout << "Rating :";
cin >> newMovie.rating;
cout << endl;
return newMovie;
}
void listMovie(MovieType movie) {
cout << "______________________________________" << endl;
cout << "Title : " << movie.title << endl;
cout << "Director : " << movie.director << endl;
cout << "Released : " << movie.year << endl;
cout << "MPAA Rating : " << movie.rating << endl;
cout << "Running time : " << movie.length << " minutes" << endl;
cout << "______________________________________" << endl;
}
void search(vector<MovieType> movieVector) {
string strSearch;
cout << endl << "Search title: ";
getline(cin, strSearch);
for (int c = 0; c < movieVector.size(); c++) {
if (movieVector.at(c).title == strSearch)
listMovie(movieVector.at(c));
}
}
int main() {
bool quit = 0;
vector<MovieType> movieVector;
while (quit == 0) {
char selection = 'f';
cout << "Main Menu:" << endl;
cout << "'a' - Add movie" << endl;
cout << "'l' - List movies" << endl;
cout << "'s' - Search by movie title" << endl;
cout << "'q' - Quit" << endl;
cout << "Please enter one of the listed commands:";
cin >> selection;
cin.ignore();
cout << endl;
if (selection == 'a')
movieVector.push_back(addMovie());
else if (selection == 'l') {
for (int c = 0; c < movieVector.size(); c++) {
listMovie(movieVector.at(c));
}
}
else if (selection == 's') {
search(movieVector);
}
else if (selection == 'q')
quit = 1;
}
return 0;
}
When an unexpected input type is entered during the addMovie function(like entering text for the int type year), it just runs through the function then loops through the menu infinitely. It appears to me that the code just stops even looking at the input stream. I have tried using cin.ignore() in many different places but it doesn't matter if there is nothing left in the stream it just keeps going.
I am using NetBeans to compile my code.
I really have no idea why it behaves like this otherwise I would offer more information but I am just curious as to why this happens, because as I said before, my professor doesn't even know why this is happening.
Any help or insight is greatly appreciated.
cin enters an error state where cin.fail() is true. In this state it just ignores all input operations. One fix is to clear the error state, but better, only use getline operations on cin, not formatted input.
E.g., instead of
cin >> newMovie.year;
… do
newMovie.year = stoi( line_from( cin ) );
… where line_from can be defined as
auto line_from( std::istream& stream )
-> std::string
{
std::string result;
if( not getline( stream, result ) )
{
// Throw an exception or call exit(EXIT_FAILURE).0
}
return result;
}
Disclaimer: code untouched by compiler.
So first off here is my code so far
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Car
{
public:
void setUp(string, int, string, bool, string);
void output();
private:
string reportingMark;
int carNumber;
string kind;
bool loaded;
string destination;
};
void input (Car *ptr);
int main()
{
Car *ptrCar = new Car;
string reportingMark = " ";
int carNumber=0;
string kind ="business";
bool loaded= true;
string destination =" ";
Car *ptr = new Car;
input(ptr);
ptr->setUp(reportingMark, carNumber, kind, loaded, destination);
ptr->output();
}
void input (Car *ptr)
{
string reportingMark;
int carNumber;
string kind;
bool loaded;
string destination;
cout << "Please input your AAR reporting mark" << endl;
cin >> reportingMark;
do
{
if (reportingMark.length() <2 || reportingMark.length() >4);
{
cout << "Invalid. Please try again."<< endl;
cout << reportingMark.length();
cin >> reportingMark;
}
}while(reportingMark.length() >= 2 || reportingMark.length() <= 4);
cout<< reportingMark << endl;
cout<< "Please input your car number." << endl;
cin >> carNumber;
cout << carNumber<<endl;
cout << "What kind of car is it?" << endl;
cin.ignore();
getline(cin,kind);
cout << kind << endl;
cout <<"Is your car loaded? (1 - yes or 0 - no)" <<endl;
cin >> loaded;
cout << loaded << endl;
if(loaded == 0)
{
cout << "Do you have a destination? If so, where? If not, type NONE" << endl;
cin.ignore();
getline(cin,destination);
}else if (loaded == 1)
{
cout << "Where is your destination?" << endl;
cin.ignore();
getline(cin,destination);
cout << destination << endl;
}
}
void Car::setUp(string rMark, int cNumber, string cKind, bool cLoaded,
string dest)
{
reportingMark = rMark;
carNumber = cNumber;
kind = cKind;
loaded = cLoaded;
destination = dest;
}
void Car::output()
{
cout << "AAR Reporting Mark:" << reportingMark << endl;
cout << "Car Number:" << carNumber << endl;
cout << "Kind:" << kind << endl;
cout << "Your car is:" << loaded << endl;
cout << "Destination:" << destination << endl;
}
What I'm struggling with is specifically that my lab asks for
A string named reportingMark to contain two to four characters
Every input I enter keeps giving me the invalid option when the number of characters in the string isn't 2-4. Even when I try inputs of 2-4 characters.
My other issue is "destination" The input I give isn't outputting my input correctly, it just appears to what I have in int main which is blank space.
You have couple of errors in the do-while loop.
do
{
if (reportingMark.length() <2 || reportingMark.length() >4);
// The ; in the above line is the end of the if statment.
// The following block of code gets executed no matter what
{
cout << "Invalid. Please try again."<< endl;
cout << reportingMark.length();
cin >> reportingMark;
}
}while(reportingMark.length() >= 2 || reportingMark.length() <= 4);
The conditional in while is not right either. It should be the same as the one in the if statement.
}while(reportingMark.length() < 2 || reportingMark.length() > 4);
You can remove the duplicate code by using:
while ( true )
{
cin >> reportingMark;
// The length is used many times. Might as well use a variable.
size_t length = reportingMark.length();
if (length >= 2 && length <= 4)
{
break;
}
cout << "Invalid length. Please try again."<< endl;
cout << length << endl;
}
When I enter this code and try to run it, it isn't working when the user selects option 1, to enter some text and a string to search for within their text. It outputs "enter text" and then "enter string to search" immediately after, without giving the user the chance to input some text. What is wrong?
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <algorithm>
using namespace std;
string s1, text;
int rand(int*);
int Array[100];
void sortArray(int[], int);
void showArray(const int [], int);
int main()
{
while (1)
// Menu to prompt user choice
{
char choice[1];
cout << endl;
cout << endl;
cout << "--MENU--" << endl;
cout << "1. Pattern Matching" << endl; // search for string within text
cout << "2. Sorting Techniques" << endl; // generate and then sort 10 random numbers
cout << "Enter your choice: " << endl;
cout << endl;
cin >> choice;
cout << endl;
if (choice[0] == '1') // string search option
{
cout << "Enter text:" << endl; // accept text from user
getline (cin, s1);
cout << "Enter string to search:" << endl; // accept string to search from user
getline (cin, text);
int pos = s1.find(text); // finds position where the string is located within text
if (pos >= 0)
{
cout << "Found '" << text << "'" << " at position " << pos + 1 << "." << endl;
}
else
{
cout << "Did not find text." << endl;
}
}
This is because cin >> choice reads part of the current input line for the choice entered by the user. The first getline() call reads the remaining part of the input line immediately following the choice entered by the user. You need to ignore the rest of the input line after the choice.
cin >> choice;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
You will also need to add #include <limits> to the beginning of your code in order to pull in numerical_limits.
It looks as though you are defining some sort of char array for the user response. I would tend to make that a non-zero integer type with an exception if the choice is neither 1 nor 2. There are also some shortcuts for output formatting that reduces lines of code. Also, you would want to include the standard string class to accept the string. Maybe try something like the following:
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
#include <algorithm>
using namespace std;
string s1, text;
int rand(int*);
int Array[100];
void sortArray(int[], int);
void showArray(const int [], int);
int main()
{
while (1)
// Menu to prompt user choice
{
int choice;
cout << "\n--MENU--\n"l;
cout << "1. Pattern Matching\n"; // search for string within text
cout << "2. Sorting Techniques\n"; // generate and then sort 10 random numbers
cout << "Enter your choice:\n";
cin >> choice+"\n";
if (choice == 1 && choice > 0 && choice != 0) // string search option
{
cout << "Enter text:" << endl; // accept text from user
getline (cin, s1);
cout << "Enter string to search:" << endl; // accept string to search from user
getline (cin, text);
int pos = s1.find(text); // finds position where the string is located within text
if (pos >= 0)
{
cout << "Found '" << text << "'" << " at position " << pos + 1 << ".\n";
}
else
{
cout << "Did not find text.\n";
}
}}}