Dev-C++ 4.9.9.2 Basic Program Error - c++

I'm making this program that takes my family member's names and gives out their horoscope. And I'm getting some errors which bugs me. The random names are just for "privacy". And yes I'm just a starter and im working with basic arrays.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
string name;
string hs[4];
hs[0] = "Aquarius";
hs[1] = "Cancer";
hs[2] = "Leo";
hs[3] = "Taurus";
cin >> name;
if name = "Harp"
{
cout << hs[0] << endl;
}
if name = "Herp"
{
cout << hs[1] << endl;
}
if name = "Derp"
{
cout << hs[2] << endl;
}
if name = "Darp"
{
cout << hs[3] << endl;
}
cout << "Press Enter To Exit This Program.";
cin.get();
return 0;
}
I keep getting this:
expected `(' before "name"
Any help would be nice.
Thanks!!

Check out proper if syntax. - missing ( and ).

the corrected program is this. Note the proper syntax of if statement
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
string name;
string hs[4];
hs[0] = "Aquarius";
hs[1] = "Cancer";
hs[2] = "Leo";
hs[3] = "Taurus";
cin >> name;
if (name == "Harp")
{
cout << hs[0] << endl;
}
if (name == "Herp")
{
cout << hs[1] << endl;
}
if (name == "Derp")
{
cout << hs[2] << endl;
}
if (name == "Darp")
{
cout << hs[3] << endl;
}
cout << "Press Enter To Exit This Program.";
cin.get();
return 0;
}

if (name == "Harp")
Pay attention to the ( and ), they are not optional. Also use == (not =, it assing the value in the right side to the left, here name will have change the contenct to "Harp", and then convert it to bool, ...)

Related

C++ Inheritance vector problem (infinite looping+ question of using vector in other class)

I'm making a surface to let the user to input information and print it out.
And this is what it looks like.
main <- menu <- Reservation
<- BookingManager <- BookingRecord
And I create a vector vector<string> CompanyName in Reservation,
This is outputdataInfo() that add CompanyName,
void Reservation::outputdataInfo()
{
string CompName;
cout << "Company Name <-" << endl;
cin >> CompName;
Reservation::setCompanyName(string (CompName) );
cout << CompanyName.at(0) << endl;
// Use for test and it works
cout << CompanyName.size() << endl;
// Use for test and it works
cout << "End of Reservation, thank you." << endl;
}
The setter of CompanyName:(worked)
void Reservation::setCompanyName(const string& cn)
{this->CompanyName.push_back(cn);}
But now BookingRecord::outputdataInfo() wants to print Booking Record.
void BookingRecord::outputdataInfo()
{
cout << " ----- Booking Record -----" << endl;
Reservation::printBookingRecord();
}
And I wrote like this(unconfirm this is correct or not):
void Reservation::printBookingRecord() {
for (int i = 0; i < CompanyName.size(); i++) {
cout << " ---- Company ---- " << endl;
cout << "Name: " << CompanyName.at(i) << endl;
}
}
But CompanyName suddenly looks like it forget anything, or like reset the size.
The result is BookingRecord::outputdataInfo() is printing infinitly non-stop, but nothing happen to the Reservation::printBookingRecord(). This is weird beacuse there suppose no for-loop in BookingRecord::outputdataInfo().
And I wanna know how to print data with (Reservation::printBookingRecord() is called by BookingRecord::outputdataInfo(), but the vector is at "Reservation")
(or vector can be use in other classes)
Big thanks :)
Source Code (kinda bit long sry)
//
// main.cpp
//
#include <iostream>
#include <string>
#include <cstdlib>
#include <vector>
#include "Menu.h"
#include "Reservation.h"
#include "BookingManager.h"
using namespace std;
int main(int argc, const char* argv[]) {
Menu m;
Reservation R;
BookingManager BM;
char choice;
do {
choice = m.menu();
switch (choice)
{
case 'R': case 'r':
R.outputdataInfo();
break;
case 'B': case 'b':
BM.outputdataInfo();
break;
default:
cout << "Invalid Alphabet. Please try again." << endl;
break;
}
} while (choice == 'R' || choice == 'r' || choice == 'B' || choice == 'b');
return 0;
}
//.....................
// Menu.h
//
#include <iostream>
#ifndef Menu_h
#define Menu_h
class Menu {
public: //Accessibility as public
char option;
char menu();
};
#endif
//.....................
// Menu.cpp
//
#include <iostream>
#include "Menu.h"
using namespace std;
char Menu::menu() {
cout << "" << endl;
cout << " BNC Exhibition Tour in European Cities" << endl;
cout << " Exhibition Recruitment " << endl;
cout << " " << endl;
cout << "Please type:" << endl;
cout << "R -> for Reservation Page" << endl;
cout << "B -> for Booking Manager Page" << endl;
cout << "And Press ENTER." << endl;
cin >> option;
cout << "" << endl;
return option;
}
//.............................
// Reservation.h
//
#include <iostream>
#include <vector>
using namespace std;
#ifndef Reservation_h
#define Reservation_h
class Reservation {
private:
vector<string> CompanyName;
public: //Accessibility as public
void outputdataInfo();
void setCompanyName(const string& cn);
Reservation();
~Reservation();
void printBookingRecord();
};
#endif
//.....................................
// Reservation.cpp
//
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <vector>
using namespace std;
#include "Reservation.h"
void Reservation::outputdataInfo()
{
cout << "Please input detail information first :" << endl;
string CompName;
cout << "Company Name <-" << endl;
cin >> CompName;
Reservation::setCompanyName(string (CompName) );
cout << CompanyName.at(0) << endl; //it works
cout << CompanyName.size() << endl; //it works
cout << "End of Reservation, thank you." << endl;
}
//////////////////////// S E T T E R ////////////////////
void Reservation::setCompanyName(const string& cn)
{
this->CompanyName.push_back(cn);
}
//////////////////////// S E T T E R ////////////////////
Reservation::Reservation() {}
Reservation::~Reservation() {}
/////////////////////// P R I N T ///////////////////////
void Reservation::printBookingRecord() {
for (int i = 0; i < CompanyName.size(); i++) {
cout << " ---- Company ---- " << endl;
cout << "Name: " << CompanyName.at(i) << endl;
}
}
//.............................
// BookingManager.h
//
#include <iostream>
#include <vector>
#ifndef BookingManager_h
#define BookingManager_h
class BookingManager {
public: //Accessibility as public
char option;
void outputdataInfo();
};
//..........................................
// BookingManager.cpp
//
#include <iostream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <vector>
#include "BookingManager.h"
#include "BookingRecord.h"
using namespace std;
void BookingManager::outputdataInfo() {
BookingRecord BR;
cout << "" << endl;
cout << " ----- Booking Manager -----" << endl;
cout << "" << endl;
cout << "Please type:" << endl;
cout << "B -> for Booking Record" << endl;
cout << "And Press ENTER." << endl;
cin >> option;
cout << "" << endl;
do {
switch (option)
{
case 'B': case 'b':
BR.outputdataInfo();
break;
default:
cout << "Invalid Alphabet. Please try again." << endl;
break;
}
} while (option == 'B' || option == 'b');
}
#endif
//...........................................
// BookingRecord.h
//
#include <iostream>
#include <vector>
#include "Reservation.h"
#ifndef BookingRecord_h
#define BookingRecord_h
class BookingRecord : public Reservation {
public: //Accessibility as public
void outputdataInfo();
};
#endif
//..........................................
// BookingRecord.cpp
//
#include <iostream>
#include <string>
#include <vector>
#include "Reservation.h"
#include "BookingRecord.h"
void BookingRecord::outputdataInfo()
{
cout << "" << endl;
cout << " ----- Booking Record -----" << endl;
cout << "" << endl;
cout << " Print all the information..." << endl;
Reservation::printBookingRecord();
}
// END
So you have two CompanyNames in your code.
One is here, part of the R variable.
int main(int argc, const char* argv[]) {
Menu m;
Reservation R;
And the other is here
void BookingManager::outputdataInfo() {
BookingRecord BR;
BookingRecord derives from Reservation, so it also contains a CompanyName.
I think it's pretty clear that you are adding a name to the CompanyName in R in main but printing out the CompanyName in BR in BookingManager::outputdataInfo.
The class design looks wrong to me.For instance there's a lack of parameters to your methods. Surely BookingManager::outputdataInfo should take a BookingRecord as a parameter to allow the caller to specify which BookingRecord they want to output. Just declaring a BookingRecord as a local variable in BookingManager::outputdataInfo doesn't make any sense.
Before you rush to write a lot of code, try and think about the design of your classes. How the different classes should relate to each other, what member variables they need, what methods they need, what parameters and return types those methods need. Think about this in terms of how your classes model the real world, not in terms of how you are going to implement functionality. That comes later, get the design right first.

function already has a body and redefinition of string variable

ERRORS:
error messages
mainFun.cpp:
#include <iostream>
#include <string>
#include "userCheckFunH.h"
using namespace std;
int yesNo;
string passName;
string userName;
string userRetrieve()
{
if (userName == "")
{
cin >> userName;
}
else
{
if (userName == "devin772" || userName == "guestacc")
{
yesNo = 1;
}
else
{
yesNo = 0;
}
}
return userName;
}
int userCheck()
{
return yesNo;
}
int main()
{
do
{
string userN;
system("cls");
// ui
cout << " DH DB " << endl;
cout << "x----------------x" << endl;
//username
cout << "username: " << endl;
cout << "> ";
// fun call
userRetrieve();
int continueP = userCheck();
cout << "" << endl;
// password
if (continueP = 1 && userRetrieve() == "devin772")
{
cout << "password:" << endl;
cout << "> ";
cin >> passName;
if (passName == "12qwaszx")
{
cout << "" << endl;
system("pause");
system("cls");
// run program
dataBaseRunP("admin");
npOpen();
cout << "" << endl;
system("pause");
return 0;
}
}
else if (continueP = 1 && userRetrieve() == "guestacc")
{
cout << "password:" << endl;
cout << "> ";
cin >> passName;
if (passName == "guestguest")
{
cout << "" << endl;
system("pause");
system("cls");
// run program
dataBaseRunP("regUser");
npOpen();
cout << "" << endl;
system("pause");
return 0;
}
}
else
{
cout << "Invalid username." << endl;
cout << "" << endl;
system("pause");
userRetrieve() = "";
userName = "";
yesNo = 0;
passName = "";
}
} while (true);
system("pause");
}
nextFun.cpp :
#include <iostream>
#include "userCheckFunH.h"
using namespace std;
string userLevel;
int dataBaseRunP(string authLevel)
{
string fileName;
if (authLevel == "regUser")
{
fileName = "user.txt";
userLevel = fileName;
}
else if (authLevel == "admin")
{
fileName = "admin.txt";
userLevel = fileName;
}
else
{
cout << "ERROR - user level not found." << endl;
system("pause");
exit(EXIT_FAILURE);
return 0;
}
exit(EXIT_SUCCESS);
return 0;
}
void npOpen()
{
string fileNpName;
fileNpName = userLevel;
fileNpName = "notepad \"" + fileNpName + "\"";
system(fileNpName.c_str());
}
userCheckFunH.h:
#ifndef USERCHECKFUN_H
#define USERCHECKFUN_H
#include "nextFun.cpp"
int dataBaseRunP();
void npOpen();
#endif
i'm attempting to make a basic program that allows you to open files hidden through windows in a basic c++ program. keep getting this error. tried different header guards, variable names, function names, file names. i also delete nextFun.cpp and the program ran fine. i can't get past this error, please help.
thanks! :)
It is highly unusual to include a cpp file, which you do in userCheckFunH.h, with
#include "nextFun.cpp"
Your nextFun.cpp file includes this very header:
#include "userCheckFunH.h"
Since you cpp file doesn't have an include guard (which is fine) you end up with the functions in the cpp file twice.
Don't include the cpp file in the header.

Placing Printed text in the same line as text before it

I'm currently making a basic program design to behave somewhat like a chell. The code is here:
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <Windows.h>
#include <Stdio.h>
#include <string>
using namespace std;
main()
{
SetConsoleTextAttribute (GetStdHandle(STD_OUTPUT_HANDLE),10);
std::string name;
std::string pass;
std::string msg;
int x = 1;
srand(time(0));
cout << "Booting up system..." << endl;
cout << "Serial Code: " << (rand()%1000) << "." << endl;
cout << "Username: ";
std::getline(std::cin, name);
cout << "Password: ";
std::getline(std::cin, pass);
cout << "" << endl;
while (true)
{
cout<<x<<": ";
std::getline(std::cin, msg);
x += 1;
if (msg == "Hello!"){
cout << "Hi!" << endl;
}
if (msg == ""){
cout << "[No Text Inserted]" << endl;
}
system ("pause");
}
And, if no text is input it displays:
1:
[No Text Inserted]
How do I get this output?
1: [No Text Inserted]
Thank you in advance!
-DJ
In your if statements, store the string into a variable and print out in the end. Also if you're comparing the same variable, I recommend using if else statements. It makes it more readable. So:
string output;
if (msg == "Hello!)
{
output = "Hi!";
}
else if (msg == "")
{
output = "[No Text Inserted]";
}
output = x.str() + ": " + output;
cout << output << endl;
Try that out and let me know if that works.
What you could do is remember input cursor position and if the input is empty string, go back to that position and print your fail message, something like this:
#include <iostream>
#include <string>
#include <windows.h>
int main()
{
HANDLE conout = GetStdHandle(STD_OUTPUT_HANDLE);
std::string input;
std::cout << "Enter something: ";
// remember cursor position
CONSOLE_SCREEN_BUFFER_INFO info;
COORD inputPos = GetConsoleScreenBufferInfo(conout, &info) ? info.dwCursorPosition : COORD{ 0, 0 };
if (!std::getline(std::cin, input) || input.empty())
{
SetConsoleCursorPosition(conout, inputPos);
std::cout << "[No Text Inserted]" << std::endl;
}
}

Wrong User Input

So I'm making a card game using C++ and I'm doing some basic user input, but I am wondering how to handle wrong user input such that you can retry without terminating the program and I'm not sure how to do that.
#include <iostream>
#include <string>
#include <stdio.h>
#include <ctype.h>
#include <algorithm>
using namespace std;
int main()
{
string command;
int i = 0;
char c;
string test1 = "help";
string test2 = "start";
cout<< "Welcome to My Card Game" << "\n";
cout<<"\n";
cout<< "For Rules please type 'rules'" << "\n";
cout<<"\n";
cout<< "To Play please type 'start'" << "\n";
getline(cin, command);
transform(command.begin(), command.end(), command.begin(),::tolower);
if(!command.compare(test1)){
cout << "You typed help" << "\n";
return 0;
}
if(!command.compare(test2)){
cout << "You typed start" << "\n";
return 0;
}
else{
cout << "Not a valid command" << "\n";
return 0;
}
}
EDIT: Solved with a simple while loop wrapped around the if-else statements.
You do not necessarily have to end the program at every single 'if'.
Also the '!' operator in your if statements is unnecessary, since it checks for inequality rather than equality.
You can try looping the program, which will make it restart if a user types in an invalid command, in your case:
#include <iostream>
#include <string>
#include <stdio.h>
#include <ctype.h>
#include <algorithm>
using namespace std;
int main() {
string command;
int i = 0;
char c;
string test1 = "help";
string test2 = "start";
cout<< "Welcome to My Card Game" << "\n";
cout<<"\n";
cout<< "For Rules please type 'rules'" << "\n";
cout<<"\n";
cout<< "To Play please type 'start'" << "\n";
while (1) {
getline(cin, command);
transform(command.begin(), command.end(), command.begin(), ::tolower);
if(command.compare(test1)){
cout << "You typed help" << "\n";
//continue code for when they type help.
}
else if (command.compare(test2)) {
cout << "You typed start" << "\n";
//continue code for when they type start.
//make sure that you break the while loop with 'break;' when they finish the game so that your program will end.
}
else {
cout << "Not a valid command" << "\n";
};
};
return 0;
};
I hope this helped.

Function not recognized within scope

I've almost finished writing a program that will detect palindromes from a file and output a new file highlighting the palindromes but I'm stuck on a really dumb error. I'm trying to write a test for one of my methods (TDD) and, for some reason, it's not recognizing the function as within the scope.
I'm calling the isPalindrome(string s) method (declared in PalindromeDetector.h) in my isPalindromeTest() method (declared in PalindromeDetectorTest.h) but, for some reason, it's not recognizing it as within the scoope.
I feel like everything should be working but it just isn't. Any help you can provide would be greatly appreciated. Below is my code:
PalindromeDetector.h
#ifndef PALINDROMEDETECTOR_H_
#define PALINDROMEDETECTOR_H_
#include <iostream>
using namespace std;
class PalindromeDetector {
public:
void detectPalindromes();
bool isPalindrome(string s);
};
#endif /* PALINDROMEDETECTOR_H_ */
PalindromeDetector.cpp
#include "PalindromeDetector.h"
#include "Stack.h"
#include "ArrayQueue.h"
#include <iostream>
#include <fstream>
#include <cassert>
#include <cctype>
#include <string>
using namespace std;
void PalindromeDetector::detectPalindromes() {
cout << "Enter the name of the file whose palindromes you would like to detect:" << flush;
string fileName;
cin >> fileName;
cout << "Enter the name of the file you would like to write the results to: " << flush;
string outFileName;
cin >> outFileName;
fstream in;
in.open(fileName.c_str());
assert(in.is_open());
ofstream out;
out.open(outFileName.c_str());
assert(out.is_open());
string line;
while(in.good()){
getline(in, line);
line = line.erase(line.length()-1);
if(line.find_first_not_of(" \t\v\r\n")){
string blankLine = line + "\n";
out << blankLine;
} else if(isPalindrome(line)){
string palindromeYes = line + " ***\n";
out << palindromeYes;
} else {
string palindromeNo = line + "\n";
out << palindromeNo;
}
if(in.eof()){
break;
}
}
in.close();
out.close();
}
bool PalindromeDetector::isPalindrome(string s){
unsigned i = 0;
Stack<char> s1(1);
ArrayQueue<char> q1(1);
while(s[i]){
char c = tolower(s[i]);
if(isalnum(c)){
try{
s1.push(c);
q1.append(c);
} catch(StackException& se) {
unsigned capS = s1.getCapacity();
unsigned capQ = q1.getCapacity();
s1.setCapacity(2*capS);
q1.setCapacity(2*capQ);
s1.push(c);
q1.append(c);
}
}
i++;
}
while(s1.getSize() != 0){
char ch1 = s1.pop();
char ch2 = q1.remove();
if(ch1 != ch2){
return false;
}
}
return true;
}
PalindromeDetectorTest.h
#ifndef PALINDROMEDETECTORTEST_H_
#define PALINDROMEDETECTORTEST_H_
#include "PalindromeDetector.h"
class PalindromeDetectorTest {
public:
void runTests();
void detectPalindromesTest();
void isPalindromeTest();
};
#endif /* PALINDROMEDETECTORTEST_H_ */
PalindromeDetectorTest.cpp
#include "PalindromeDetectorTest.h"
#include <cassert>
#include <iostream>
#include <fstream>
#include <cctype>
#include <string>
using namespace std;
void PalindromeDetectorTest::runTests(){
cout << "Testing palindrome methods... " << endl;
detectPalindromesTest();
isPalindromeTest();
cout << "All tests passed!\n" << endl;
}
void PalindromeDetectorTest::detectPalindromesTest(){
cout << "- testing detectPalindromes()... " << flush;
fstream in;
string fileName = "testFile.txt";
in.open(fileName.c_str());
assert(in.is_open());
cout << " 1 " << flush;
ofstream out;
string fileOutName = "testFileOut.txt";
out.open(fileOutName.c_str());
assert(out.is_open());
cout << " 2 " << flush;
cout << " Passed!" << endl;
}
void PalindromeDetectorTest::isPalindromeTest(){
cout << "- testing isPalindrome()... " << flush;
// test with one word palindrome
string s1 = "racecar";
assert(isPalindrome(s1) == true); // these are not recognized within the scope
cout << " 1 " << flush;
// test with one word non-palindrome
string s2 = "hello";
assert(isPalindrome(s2) == false); // these are not recognized within the scope
cout << " 2 " << flush;
// test with sentence palindrome
string s3 = "O gnats, tango!";
assert(isPalindrome(s3) == true); // these are not recognized within the scope
cout << " 3 " << flush;
// test with sentence non-palindrome
string s4 = "This is not a palindrome.";
assert(isPalindrome(s4) == false); // these are not recognized within the scope
cout << " 4 " << flush;
cout << " Passed!" << endl;
}
isPalindrome is a member function of PalindromeDetector, but you are trying to call it from within a PalindromeDetectorTest method. If the test class derived from PalindromeDetector this would work, but there isn't (and almost certainly shouldn't be) any such relationship between them.
You need a PalindromeDetector object to call the method on. Probably just as simple as this:
void PalindromeDetectorTest::isPalindromeTest(){
cout << "- testing isPalindrome()... " << flush;
PalindromeDetector sut; // "subject under test"
// test with one word palindrome
string s1 = "racecar";
assert(sut.isPalindrome(s1) == true);
// etc.
}
You could also make the PalindromeDetector methods static since the object doesn't appear to have any state. Then you could simply call PalindromeDetector::isPalindrome(s1); without the need to create an instance.