robotnixon 0 Light Poster

Thanks smantscheff.

I figured it out. Just needed to remove the first 2 lines, add semicolons to the next two, and remove the AS [MATCH] from line 16.

robotnixon 0 Light Poster

Hey everyone.

I have a mysql project that requires only some basic queries except one. Nothing more challenging than some really basic select/insert statements. No problem there. But the one complex one isn't working out.

I typically work a little with SQL server and wrote the following at work in SQL management studio. The code works fine there, but gets several syntax errors when I run it in phpmyadmin.

If anyone can give me tips on how to convert it over I'd appreciate it. It checks a user's lists of movies, finds someone else who likes at least 2 of the same films and then shows the first user a list of the second user's films. Sort of a suggestion system based on similar users.

DECLARE @UserName AS VARCHAR(50) 
DECLARE @MinMatch AS INT
SET @UserName = 'John' 
SET @MinMatch = 2

SELECT
Title

FROM
Movies INNER JOIN
(
                SELECT

                UserName,
                Count(Title) AS [Match]
                FROM Movies

                WHERE
                Title IN
                (
                Select
                Title
                
                FROM
                Users INNER JOIN Movies ON Users.UserName=Movies.UserName

                WHERE

                Users.UserName = @UserName 
                )
                AND UserName <> @UserName  
                GROUP BY UserName
                HAVING

                Count(Title) >= @MinMatch

) AS Recommend ON Movies.UserName = Recommend.UserName

WHERE
Title NOT IN
(
                SELECT
                Title

                FROM
                Users INNER JOIN Movies ON Users.UserName=Movies.UserName

                WHERE
                Users.UserName = @UserName 

)
robotnixon 0 Light Poster

Big thanks to all three of you. Got it working.

robotnixon 0 Light Poster

Quick question (hopefully). I have a vector of strings and need to remove duplicates. Normally, I'd just use sort, erase and unique. However, I don't want to sort the data. My idea was to copy the vector to a set, then back to a vector. But every attempt just screws up the order. My last attempt involved copying the vector to a set, copying the set to another vector by using back_insert, and then reversing the vector. Doesn't work. I'd appreciate any ideas on how to solve this. Thanks. Here's the last attempt:

copy(v.begin(), v.end(), inserter(s, s.end()));
copy(s.begin(),s.end(), back_inserter(newV));
reverse(newV.begin(),newV.end());
robotnixon 0 Light Poster

So I'm working on a C++ program and part of it involves converting decimal numbers to hexadecimal. I have been using printf("%02X",number) to do this, but I'd like to print to a text file. Just wondering if anyone knew of a way to send formatted text to file rather than the screen. I've been trying to use fprintf with no luck. Any suggestions would be appreciated. I'll also post code if anyone deems it relevant. Thanks.

robotnixon 0 Light Poster

Program is supposed to be an database that responds to SQL-type commands. So the first choice is what you'd like to see (Flight numbers for example) from an airline(again for example). So choosing flight numbers, and then Nadir, should return
122
129
I've been testing what I have so far so a few option are missing until I get over this hurdle.

Full code:

#include<iostream>
#include<string>

using namespace std;


void searchString(string A[],int size, string answer)
{
	int j;
	
	for(j=0; j < size; j++)
		if(A[j] == answer)
		
			cout << A[j] << endl;
		   
		
		else cout << "Not Found"<< endl;
	
}

int main()
{
	string airLine[5] = {"Nadir", "Acme", "Acme", "Acme", "Nadir"};
	string flightNum[5] = {"122", "221", "122", "323", "199"};
	string gate[5] = {"34", "22", "33", "34", "13"};
	string destination[5] = {"Detroit", "Denver", "Anchorage", "Honolulu", "Detroit"};
	string departTime[5] = {"08:10","08:17", "08:22", "08:30", "08:47"}; 
	string sTemp[5];
	

	int firstChoice;
	int secondChoice;
	string answer;

	cout << "Welcome to the Flight Database" << endl;
	cout << "Please choose the category you'd like to see from the following list." << endl;
	cout << "1. Airline" << endl;
	cout << "2. Flight Number" << endl;
	cout << "3. Gate" << endl;
	cout << "4. Destination" << endl;
	cout << "5. Departure Time" << endl;

	cin >> firstChoice;
	switch(firstChoice)
	{
	case 1:     sTemp[0] = airLine[0];
				sTemp[1] = airLine[1];
				sTemp[2] = airLine[2];
				sTemp[3] = airLine[3];
				sTemp[4] = airLine[4];
				
				break;
		case 2: sTemp[0] = flightNum[0];
				sTemp[1] = flightNum[1];
				sTemp[2] = flightNum[2];
				sTemp[3] = flightNum[3];
				sTemp[4] = flightNum[4]; …
robotnixon 0 Light Poster

passing like this:

searchString (sTemp, 5, answer)

And the array contains the following:

string airLine[5] = {"Nadir", "Acme", "Acme", "Acme", "Nadir"};

sTemp is a copy of the airLine array. I've substituted airLine in the call and had the same results.

robotnixon 0 Light Poster

I have a funny feeling this is a stupid question so bear with me. I'm passing a string array to a function to search for elements in it. I have what is written below, and all it does is print "Not Found" five times. I'd also like it to print out each occurrence of the target. I've been playing with it for too long and am getting nowhere. I've echo printed all of the variables to be sure they're being read but somethings still not right. I'd appreciate any help. Thanks.

void searchString(string A[],int size, string target)
{
	int j;
	{
	for(j=0; j < size; j++)
		if(A[j] == target)
			cout << A[j] << endl;
		else cout << "Not Found";
	}
}
robotnixon 0 Light Poster

Okay I got it. Just needed to move the cout statements to the front of the function and use a static int. Which I had never used before (thanks vmanes). Tried something similar before but just kept getting 1's. And to clarify I did need to count every recursive call being made. Thanks again.

robotnixon 0 Light Poster

I'm having a tough time conceptualizing this problem. I have a recursive function computing the number of possible combinations of two numbers. I have it working fine, just need one thing sorted out. My output needs a counter to increment each recursive step. Like this:

Level 1:
...
Level 2
...
Level 3
...

The combinations are printing out correctly but I can't figure out how to increment the level correctly each time. Any help would be appreciated. Here's the code:

#include<iostream>

using namespace std;


long Combinations(int y,int x,int level) 

{
	if(x==1)
	{
		return y;
	}
	else if(x==y)
	{
		return 1;
	}
	else 
	{
		cout << "Recursive Level " << level << endl;
		cout << "y = " << y << "  x = " << x << endl;
		return Combinations(y-1,x-1,level+1) + Combinations(y-1,x,level); 
		
		}
}


int main()
{
	
	long result;   
    result = Combinations(8,4,1); 
	cout << result << endl;

 return 0;
}
robotnixon 0 Light Poster

Got it.

Needed to move the function below both class declarations in order to get the compiler to recognize Grade. operator== function is working as well. Thanks again Ancient Dragon. Here's the completed code:

#include<iostream>

using namespace std;
const int MAX_GRADES = 4;

 

class Student;

class Teacher
{
private:
	int Id;
	float Salary;
public:
	float calculateGrade(Student& s);
	
	friend class Student;
	};

class Student
{
	private:
		int Id;
		float FinalGrade;
		float Grade[MAX_GRADES];

	public:
		void setId(int i){Id = i;};
		void setGrade(float stu[])
		{
			  for (int i=0;i<MAX_GRADES;i++)
            //   cout << stu[i]<< endl;
			   Grade[0] = stu[0];
			   Grade[1] = stu[1];
			   Grade[2] = stu[2];
			   Grade[3] = stu[3];
			     
		};
	bool operator==(Student& a)
	{
		if(a.FinalGrade == FinalGrade)
			return true;
		else 
			return false;
		
	};
		friend class Teacher;

};

float Teacher::calculateGrade(Student& s)
{
		float FinalGrade;
	    FinalGrade = s.Grade[0] + s.Grade[1] + s.Grade[2] + s.Grade[3]; 
		return FinalGrade;
		
}

int main()
{
float g1[] = {10.0, 20.0, 25.0, 25.0};
float g2[] = {25.0, 20.0, 10.0, 25.0};
Student x, y;
x.setGrade(g1);
y.setGrade(g2);

Teacher z;

cout << z.calculateGrade(x) << endl;
cout << z.calculateGrade(y) << endl;

if(x==y)

cout << "Students x and y have the same grade !" << endl;
else
cout << " Students x and y don’t have the same grade !" << endl;

return 0;


}
robotnixon 0 Light Poster

Sorry AD. In another thread you added line numbers to my code so I tried to add them, but used the wrong button.

#include<iostream>

using namespace std;
const int MAX_GRADES = 4;

class Student;   //needs to let teacher know about class

class Teacher
{
private:
	int Id;
	float Salary;
public:
	float calculateGrade(Student)
	{
	  	float FinalGrade;
		//FinalGrade = Grade[0] + Grade[1] + Grade[2] + Grade[3]; 
		return FinalGrade;
	}
	//friend class Student;
	};

class Student
{
	private:
		int Id;
		float FinalGrade;
		float Grade[MAX_GRADES];

	public:
		void setId(int i){Id = i;};
		void setGrade(float G[])
		{
			  for (int i=0;i<MAX_GRADES;i++)
               cout << G[i]<< endl;
			   Grade[0] = G[0];
			   Grade[1] = G[1];
			   Grade[2] = G[2];
			   Grade[3] = G[3];
			     
		};
	//	bool operator == (Student& x,y){if x.FinalGrade == y.FinalGrade return true; else return false;};
		friend class Teacher;

};

int main()
{
float g1[] = {10.0, 20.0, 25.0, 25.0};
float g2[] = {25.0, 20.0, 10.0, 25.0};
Student x, y;
x.setGrade(g1);
y.setGrade(g2);

Teacher z;

cout << z.calculateGrade(x) << endl;
cout << z.calculateGrade(y) << endl;

//if(x==y)

//cout << " Students x and y have the same grade !" << endl;
//else
//cout << " Students x and y don’t have the same grade !" << endl;

return 0;


}
robotnixon 0 Light Poster

I followed most of Ancient Dragon's suggestions (leaving operator for later) but still getting the error that Grade is an undeclared identifier. Tried making it a public but that did nothing (kind of expected that). The code works fine with all of the calculateGrade stuff commented out so that seems to be the trouble spot. Here's the revised code: Any help would be appreciated.

[LIST=1]
[*]#include<iostream>

[*]using namespace std;
[*]const int MAX_GRADES = 4;

[*]class Student;   //needs to let teacher know about class

[*]class Teacher
[*]{
[*]private:
[*]	int Id;
[*]	float Salary;
[*]public:
[*]	float calculateGrade(Student)
[*]	{
[*]	  	float FinalGrade;
[*]		FinalGrade = Grade[0] + Grade[1] + Grade[2] + Grade[3]; 
[*]		return FinalGrade;
[*]	}
[*]	friend class Student;
[*]	};

[*]class Student
[*]{
[*]	private:
[*]		int Id;
[*]		float FinalGrade;
[*]		float Grade[MAX_GRADES];

[*]	public:
[*]		void setId(int i){Id = i;};
[*]		void setGrade(float G[])
[*]		{
[*]			  for (int i=0;i<MAX_GRADES;i++)
[*]               cout << G[i]<< endl;
[*]			   Grade[0] = G[0];
[*]			   Grade[1] = G[1];
[*]			   Grade[2] = G[2];
[*]			   Grade[3] = G[3];
[*]			     
[*]		};
[*]	//	bool operator == (Student& x,y){if x.FinalGrade == y.FinalGrade return true; else return false;};
[*]		friend class Teacher;

[*]};

[*]int main()
[*]{
[*]float g1[] = {10.0, 20.0, 25.0, 25.0};
[*]float g2[] = {25.0, 20.0, 10.0, 25.0};
[*]Student x, y;
[*]x.setGrade(g1);
[*]y.setGrade(g2);

[*]Teacher z;

[*]cout << z.calculateGrade(x) << endl;
[*]cout << z.calculateGrade(y) << endl;

[*]//if(x==y)

[*]//cout << " Students x and y have the same grade !" << endl;
[*]//else …
robotnixon 0 Light Poster

Having some trouble with converting my driver input from one class to the friend class and then summing the array. My setGrade function is reading the input correctly (I think, the numbers match up) but I need to pass the class to the friend in order to add up the values. Herein lies the aggravation. The errors I've been getting are that Grade is an undeclared identifier, or that I can't make the conversion from the setGrade variable to something I can work with in the other class. I'll also need to use the '==' operator eventually but I'd rather get to that after I deal with the previous mess. That said however, I'd appreciate any advice anyone could give me. Thanks in advance. Here's the code:

[LIST=1]
[*]#include<iostream>

[*]using namespace std;
[*]const int MAX_GRADES = 4;

[*]class Student;

[*]class Student
[*]{
[*]	private:
[*]		int Id;
[*]		float FinalGrade;
[*]		float Grade[MAX_GRADES];

[*]	public:
[*]		void setId(int i){Id = i;};
[*]		void setGrade(float G[])
[*]		{
[*]			for (int i=0;i<MAX_GRADES;i++)
[*]				cout << G[i]<< endl;
[*]		};
[*]	//	bool operator == (Student x,y){if x.FinalGrade == y.FinalGrade return true; else return false;};
[*]		friend class Teacher;

[*]};
[*]class Teacher
[*]{
[*]private:
[*]	int Id;
[*]	float Salary;
[*]public:
[*]	float calculateGrade(Student G[])
[*]	{
[*]		float FinalGrade = 0;
[*]		Grade[0] = G[0];
[*]		Grade[1] = G[1];
[*]		Grade[2] = G[2];
[*]		Grade[3] = G[3];
[*]		
[*]		FinalGrade = Grade[0] + Grade[1] + Grade[2] + Grade[3]; 
[*]		return …
robotnixon 0 Light Poster

Made some changes with VernonDozier's recommendations (thanks for all the information) but still getting a logic error with setRaceCarStatus My specs have it as taking a boolean parameter and returning nothing, so I've tried putting an if-else statement but it doesn't seem to be working since the answer is always true. Here's the relevant code section:

void Car::setRaceCarStatus(bool)
{
	
	if(true)
	RaceCarStatus = true;
	else if (false)
	RaceCarStatus = false;
}

And here's the call in main

cout << "Initial race car status for y: " << y.getRaceCarStatus()<< endl;
y.setRaceCarStatus(true);
cout << "Modified race car status for y " << y.getRaceCarStatus() << endl;

I've played with it for about an hour but can't get it to work right.

robotnixon 0 Light Poster

So RaceCarStatus is no longer a function, and along with a couple minor changes it compiles. However I'm getting the same result for RaceCarStatus before and after input. Part of the spec is having a copy constructor which may be affecting the result but I'm not sure what it does in this particular program. Here's the modified code. Thanks so far everybody.

[LIST=1]
[*]#include<iostream>

[*]using namespace std;

[*]class Vehicle
[*]{
[*]public:
[*]	
[*]	
[*]	Vehicle();           //constructor, sets Age and Price to 0
[*]	~Vehicle();        //destructor, sets Age andPrice to 0
[*]	void setAge(int i){Age = i;}; //takes integer and sets Age to int value
[*]	void setPrice(float i) {Price = i;};//takes float value, sets Price to value
[*]	int getAge()const;
[*]	float getPrice()const;
[*]     

[*]private:
[*]	int Age;

[*]protected:
[*]	float Price;

[*]};

[*]Vehicle::Vehicle()
[*]{
[*]	Age = 0;
[*]	Price = 0;
[*]}

[*]Vehicle::~Vehicle()
[*]{
[*]	Age = 0;
[*]	Price = 0;
[*]}

[*]int Vehicle::getAge() const
[*]{
[*]	return Age;
[*]}

[*]float Vehicle::getPrice() const
[*]{
[*]	return Price;
[*]}

[*]class Car : public Vehicle
[*]{

[*]public: bool RaceCarStatus;//boolean, yes or no
[*]	Car();                  //default constructor, sets RaceCarStatus=false                  
[*]		     //need copy constructor, takes one parameter of class car
[*]	~Car();               //destructor
[*]	void setRaceCarStatus(bool);//takes boolean parameter, returns nothing
[*]	bool getRaceCarStatus()const;//no parameters, returns status
[*]};

[*]Car::Car()
[*]{
[*]	int i;
[*]	i = 0;
[*]}

[*]Car::~Car()
[*]{
[*]	int i; 
[*]	i = 0;
[*]}

[*]void Car::setRaceCarStatus(bool)
[*]{
[*]	
[*]	RaceCarStatus = false;
[*]}

[*]bool Car::getRaceCarStatus() const
[*]{ …
robotnixon 0 Light Poster

My professor gave us a set of class specifications for three classes. Vehicle, Car, and Truck. My vehicle class works fine, and utilizing it in the other classes is fine as well but I'm having trouble implementing the individual class specifications in the other two. Really the only thing I have to do is somehow say whether or not the car is a race car. I've never worked with boolean functions (just never had to so far) so another problem is that I'm not sure about how to write the driver in main either. Any help would be appreciated.

Code posted below. I'm going one class at a time so the truck class is empty but I'll fill that in once Car is taken care of. Any input anywhere though would be very helpful. Thanks in advance.

[LIST=1]
[*]#include<iostream>

[*]using namespace std;

[*]class Vehicle
[*]{
[*]public:
[*]	
[*]	
[*] Vehicle();                 
[*] ~Vehicle();                
[*] void setAge(int i){Age = i;}; 
[*] void setPrice(float i) {Price = i;};
[*] int getAge()const;
[*] float getPrice()const;
[*]     

[*]private:
[*]	int Age;

[*]protected:
[*]	float Price;

[*]};

[*]Vehicle::Vehicle()
[*]{
[*]	Age = 0;
[*]	Price = 0;
[*]}

[*]Vehicle::~Vehicle()
[*]{
[*]	Age = 0;
[*]	Price = 0;
[*]}

[*]int Vehicle::getAge() const
[*]{
[*]	return Age;
[*]}

[*]float Vehicle::getPrice() const
[*]{
[*]	return Price;
[*]}

[*]class Car : public Vehicle
[*]{

[*]public: 
       bool RaceCarStatus()const;  //boolean, yes or no
[*]   Car();  //default constructor, sets RaceCarStatus=false                  
[*]   //need copy constructor, takes one parameter of class car …
robotnixon 0 Light Poster

I got the write to file function working. Just need to finish up the delete function. In case anyone was paying attention.

[LIST=1]
[*]Card card[100];
[*]string newFile;
[*]int num = 0;
[*]int counter = 0;
[*]int i = 0;
[*]int j = 0;

[*] Card temp;
[*] ifstream inFile;
[*] inFile.open("rolodex.txt");
[*] 
[*]    cout << "Enter the file name:";
[*]	cin >> newFile;
[*]	ofstream outFile(newFile.c_str());
[*]	while(!inFile.eof())
[*] { 
[*]	 counter+= 1;
[*] 
[*]  inFile >> card[i].lastName;
[*]  inFile >> card[i].firstName;
[*]  inFile >> card[i].phoneNumber;
[*]  inFile >> card[i].eMail;
[*]  i++;
[*] }
[*] 
[*] outFile << counter - 2 << endl;
[*] for (i=1; i < counter; i++)
[*] {
[*]  outFile << card[i].lastName << " " << card[i].firstName << " " << card[i].phoneNumber <<" " << card[i].eMail<<endl;
[*] }
[*] inFile.close();
[*]  outFile.close();
[*]  cout << endl;
[*]  cout << newFile << " has been written" << endl;

[*]}
[/LIST]
robotnixon 0 Light Poster

On line 182, every time you output you also output a newline character.

That would just print them all on one line. Like this:

lastfirstphoneemaillastfirstphoneemaillastfirstphoneemail...

But thanks for the tip. I should have noticed that earlier.

robotnixon 0 Light Poster

So below is a working program I wrote that mimics a rolodex. It stores the information on a text file with the number of cards listed at the top of the file and one card per line like this:


last first phone email
last first phone email
...

I'm currently storing the information on the text file, and that's become a problem. Per the assignment, I need to be storing the data on the text file and in an array of structs. I have arrays, and I have structs. They are not however, mingling. 4 of the 6 functions work fine, but I'm hesitant to mess with the last two if my data handling is a big problem.

Writing the data to file is reading in the data, but writing out like this:
last
first
phone
email
last
...
And I haven't started the delete card function because I can't visualize what my data is going to look like in an array of structs. Any help would be appreciated and let me know if there's anything else I should change. Thanks.

[LIST=1]
[*]#include<iostream>
[*]#include<string>
[*]#include<fstream>
[*]using namespace std;



[*]struct Card
[*]{
[*]	string firstName;
[*]	string lastName;
[*]    string phoneNumber;
[*]	string eMail;
[*]};



[*]void PrintMenu();                                //displays menu of options
[*]void cardCount();                                //reads number of cards from text file
[*]void readCard();                                 //reads card from file (option 1)
[*]void writeToFile();                              //writes to the file (option 2) …
robotnixon 0 Light Poster

It works. Thank you guys so much. I thought I was just digging a hole for a while there. I still need to loop the main until 0 is input but I'm sure I can handle that. Thank you again.

robotnixon 0 Light Poster

# int convertToDecimal(string&)
# {
# char roman[20];
Try
int convertToDecimal(char roman[20])

Or better yet, make roman your std::string variable.

By leaving the parameter unnamed, you're passing a value, but totally ignoring it.

Do you have a debugger?
If so, now is the time to get used to using it.

I tried debugging with the visual studio 2005 debugger and it was reading junk values (-50 for every one). I tried changing the parameter to what you suggested but it couldn't compile since the parameter was changing the 'std::string' to 'char []'. I'm getting very confused.
I've isolated the function, and this code works fine on its own. Just can't get it to play with the rest of the program. I don't know if this will help but I'll post anyway.

#include <iostream>
#include <string>
using namespace std;

int convertToDecimal(int&);
int sum;

int main ()
{
cout << "Enter a roman numeral: ";

convertToDecimal(sum);

cout << "The decimal number is: " << sum << endl;

return 0;
}



int convertToDecimal(int& sum)
{
	char romanNumb[20];
	
	cin >> romanNumb;
	int length = strlen(romanNumb);
	int number = 0;
	int counter = 0;
	
	

	for (counter = length; counter >= 0; counter--)
	{
		if (romanNumb[counter] == 'M')
			number = 1000;
		else if (romanNumb[counter] == 'D')
			number = 500;
		else if (romanNumb[counter] == 'C')
			number = 100;
		else if (romanNumb[counter] == 'L')
			number = 50;
		else if (romanNumb[counter] == 'X')
			number = 10;
		else if (romanNumb[counter] == 'V')
			number …
robotnixon 0 Light Poster

My output being in the right format means it looks like this after running it:

Enter a roman expression
X + X
=
Enter a roman expression.

Post #3 has the old output.

I had changed all of the romanNums to roman and sum is initialized as 0 in convertToDecimal. I did what you suggested with cout statement, and my output was 50 lines, with one zero per line. Here's the revised code

[LIST=1]
[*]#include<iostream>
[*]#include<string>
[*]#include<iomanip>

[*]using namespace std;
[*]int sum;
[*]int solution;
[*]int result;

[*]int convertToDecimal(string&)
[*]{
[*]	
[*]	char roman[20];
[*]	int length = strlen(roman);
[*]	int number = 0;
[*]	int counter = 0;
[*]	int sum = 0;
[*]	
[*]	for (counter = length; counter >= 0; counter--)
[*]	{
[*]		if (roman[counter] == 'M')
[*]			number = 1000;
[*]		else if (roman[counter] == 'D')
[*]			number = 500;
[*]		else if (roman[counter] == 'C')
[*]			number = 100;
[*]		else if (roman[counter] == 'L')
[*]			number = 50;
[*]		else if (roman[counter] == 'X')
[*]			number = 10;
[*]		else if (roman[counter] == 'V')
[*]			number = 5;
[*]		else if (roman[counter] == 'I')
[*]			number = 1;
[*]		else
[*]			number = 0;

[*]		sum = sum + number;
[*]		
[*]		cout << sum << endl;
[*]}
[*]	
[*]	return sum;
[*]}

[*]string convertToRoman (int solution)
[*] {
[*]    string roman = "";
[*]    
[*]	while (solution >=1000)
[*] {
[*]        roman+="M";
[*]        solution = solution …
robotnixon 0 Light Poster

I changed this:

int convertToDecimal(string&)
{
	
	char roman[20];
	int length = strlen(roman);

My output is in the correct format but there's no answer.

robotnixon 0 Light Poster

You never use the values passed to convertToDecimal() in the form of roman. Instead, you ask for additional input in the form of romanNum.

I'm not sure I understand this part. I pass the value as a string to convertToDecimal and need to return an integer but can't redefine things. I used the length member function to read from the string but convert the characters individually and sum the values. Is the parameter wrong, or should I change the function?

robotnixon 0 Light Poster

Per the assignment we don't have to account for subtraction values. So IV and VI = 6.

And my example was bad and confusing, sorry. I input three capital X's (not a multiplication lower x) but it doesn't matter as far as running the program. Any input, outputs nothing. So even X + V leaves a blank after =. But I don't get the = until I input 3 values on 3 separate lines. So more accurately:

X + V ->program waits until two more characters are input
here
and here, then
=

or

X
+
V
=
Press any key...

Hopes this clears it up.

robotnixon 0 Light Poster

First off, happy thanksgiving everybody. Second, my program has problems. I've discovered a horrible way (for me anyway) to design and my attempts to fix it aren't getting any where. I have to design a roman numeral calculator (input romans, output romans) with at least two functions (decimal->roman, roman->decimal). I started by designing three programs, a calculator, a decimal converter, and a roman converter, and thought I'd combine them later. All three worked fine independently, but as I've learned, combining them has been difficult.
The program compiles and runs but takes 3 inputs, on 3 separate lines, and gives me nothing back. Example:

Enter a roman expression.
X
X
X
=
Press any key to continue...

What I want:
Enter a roman expression
V + VI
= XI


Here's my code. Any help will be greatly appreciated.

[LIST=1]
[*]#include<iostream>
[*]#include<string>
[*]#include<iomanip>

[*]using namespace std;
[*]int sum;
[*]int solution;
[*]int result;

[*]int convertToDecimal(string roman)
[*]{
[*]	char romanNum[100];
[*]	
[*]	cin >> romanNum;
[*]	int length = strlen(romanNum);
[*]	int number = 0;
[*]	int counter = 0;
[*]	
[*]	for (counter = length; counter >= 0; counter--)
[*]	{
[*]		if (romanNum[counter] == 'M')
[*]			number = 1000;
[*]		else if (romanNum[counter] == 'D')
[*]			number = 500;
[*]		else if (romanNum[counter] == 'C')
[*]			number = 100;
[*]		else if (romanNum[counter] == 'L')
[*]			number = 50;
[*]		else if (romanNum[counter] == 'X')
[*] …
robotnixon 0 Light Poster

That's a good question. I wanted to get the math figured out first, then tackle the exit. Probably by adding 'c' as an option in the high/low question, and then another else if statement. But that will still cause it to echo print the last guess afterwards. And won't exit the loop. Any suggestions?

Fixed it I think. Added the following statements:

[LIST=1]
[*]else if (answer == 'c')
[*]{
[*]    cout << "Got it " << firstName << endl;
[*]    numGuesses = NUMBER_OF_GUESSES +1;
[*]}
[*]else
[*]{
[*]    cout << "Try again. Next time press l, h, or c." << endl;
[*]    numGuesses = NUMBER_OF_GUESSES +1;
[*]}[/LIST]

Exits the loop without reprinting the last guess and added another exit in case of user error.

Thanks again for your help AD and Val. Reps to both of you. I'll test it out tonight and mark it solved if I don't have any trouble.

robotnixon 0 Light Poster


How does the game end if the computer actually guesses the number?

That's a good question. I wanted to get the math figured out first, then tackle the exit. Probably by adding 'c' as an option in the high/low question, and then another else if statement. But that will still cause it to echo print the last guess afterwards. And won't exit the loop. Any suggestions?

robotnixon 0 Light Poster

you are close -- delete lines 36 and 46. Then delete the +1 from line 37 and the -1 from line 45. and line 45 should be min = computerGuess Finally, line 47 calculation is incorrect.

computerGuess = ((max - min)/2 ) + min;

Did all of that and had the same problem. However, changed line 45 to max = computerGuess and that did the trick. With those changes it left me with max as an undeclared variable. So I set the values for max and min to 100 and 1. Not sure if those messed with your suggestion. Thanks a lot for your help.

robotnixon 0 Light Poster

Having some trouble with my number guessing game. The object is that the user thinks of a number between 1 and 100 and the computer tries to guess it in a set number of tries. The user inputs an "l" or an "h" if the guess is too low or too high, respectively. My problem is switching between the two. The first guess is always 50, so if that's too low it guesses 75. If that's too low, it guesses 88. Which works fine, except if you pick, let's say, 60. First guess 50. press "l" next guess 75, press "h" next guess is 37.

I've tried creating a new variable in order to reset the computer's guess each time through the loop but with no luck. Any help in the right direction would be appreciated.
Here's the code:

#include <iostream>
#include <string> 

using namespace std;
const int NUMBER_OF_GUESSES = 5;

int main()
{
    string firstName;
    int computerGuess;
    int numGuesses = 1;
    char answer;
    int max;
    int min;

cout << "What is your first name?" << endl;

cin >> firstName;

cout << firstName << ", please think of a number between 1 and 100, and I will try to"   << endl; 
cout << "guess the number in 5 attempts." << endl << endl;

cout << "Press h if I've guessed too high or l if I've guessed too low." << endl << endl;

computerGuess = 50;

while (numGuesses <= 5)

{
    cout << "Is the number " …
robotnixon 0 Light Poster

I'll work on it. Thanks for the pointers WaltP. I got bracket-shy because the missplaced bracket in the OP was silly and time-consuming. But you are right. Thanks again.

robotnixon 0 Light Poster

Here's the whole thing. I'm submitting it today so if there's any fine tuning that needs to be done or if you'd just like to yell at me feel free. WaltP- I tried spacing stuff out and lining things up but really didn't add many brackets because they've been a sore spot with me. Any suggestions you (or anyone else) have further regarding the formatting are welcome and appreciated. Thanks again everyone.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

const int Size = 20;
void displayGrid(const bool [][Size]);
void nextGen(bool [][Size], bool [][Size]);
int getNeighborCount(const bool [][Size], int, int);

int main()
{
    ifstream datafile;
    string filename;
  
  cout << "The input values from the file will begin the first generation." << endl << endl;
  cout << "Follow the prompts to create new generations or terminate the program." << endl << endl;
   
  // Initilize the grid to all dead cells
  bool Grid[Size][Size];

  for (int i=0; i < Size; i++)
  for (int j=0; j < Size; j++)
      
     Grid[i][j] = false;

  int row, col;

  // Prompt user for filename.
  
    cout << "Please enter the file name containing input values. " << endl; 
    cout << endl;
    cin >> filename;

    cout << fixed << showpoint;

    datafile.open(filename.c_str());
    if (!datafile)
    {
        cout << "File not found" << endl;
        return 1;
    }
    while (datafile)
    {
        datafile >> row >> col;
    
    if ( row>=0 && row<Size && col>=0 && col<Size)  // checks for compatability
      Grid[row][col] = true;
    }
   while ( row != -1);
    
  displayGrid(Grid); 

  char answer; 
  
  bool …
robotnixon 0 Light Poster

I don't think I understand. What does this code do?

calls a getNeighborCount function and loops a local array through to a temporary world. This part decides in the temp world if the cell will live or die. After that decision is made, the temporary world gets copied over to the next generation.

if (neighborcount == 2)             // 2 neighbors 
    tempWorld[i][j] = World[i][j];  // stays alive.
      else if (neighborcount == 3)        
    tempWorld[i][j] = true;         // 3 neighbors:
                                        // stays alive

      else tempWorld[i][j] = false;      // 1 and 4+ neighbors:

Doesn't it test for 3 neighbors?

Yes it does, but the three cells should populate a fourth. The repopulating thing is bugging me.

And please format your code better -- it's a little hard to follow. You need more {}'s and proper indentation to make it easier to read.

I'm reformatting right now. I agree that it is hard to read and apologize. I'll repost as soon as I'm done. Thanks for telling me. I'm sure that would have cost me points.

robotnixon 0 Light Poster

i have code for basically this exact thing in VB but using arrays if you are interested

Sure I'll take a look. I'd like to see another way of doing it. Thanks.

robotnixon 0 Light Poster

Thanks a lot. It's reading the file just fine now but I noticed another problem after running through a couple generations. I neglected to include a command to populate a cell with three neighbors. No kids means everyone just slowly dies out. Here's the relevant code (let me know if you need more):

void nextGen(bool World[][Size], bool tempWorld[][Size])
{
  int neighborcount;
  for (int i=0; i < Size; i++)
    for (int j=0; j < Size; j++) {
      neighborcount = getNeighborCount(World,i,j);
      if (neighborcount == 2)             // 2 neighbors 
    tempWorld[i][j] = World[i][j];  // stays alive.
      else if (neighborcount == 3)        
    tempWorld[i][j] = true;         // 3 neighbors:
                                        // stays alive

      else tempWorld[i][j] = false;      // 1 and 4+ neighbors:
    }                                    // dead

  // copy tempWorld to World
  for (int i=0; i < Size; i++)
    for (int j=0; j < Size; j++)
      World[i][j] = tempWorld[i][j];
}

int getNeighborCount(const bool World[][Size], int row, int col)

// Counts neighbors in a row/column pair
{

  int count=0;

  if (row > 0) {
    if (col > 0 && World[row-1][col-1] == true)          
      count++;
    if (col < Size-1 && World[row-1][col+1] == true)     
      count++;
    if (World[row-1][col] == true)                       
      count++;
    
  }

  if (row < Size - 1) {
    if (col > 0 && World[row+1][col-1] == true)          
      count++;
    if (col < Size - 1 && World[row+1][col+1] == true)  
      count++;
    if (World[row+1][col] == true)                       
      count++;
  }

  if (col > 0 && World[row][col-1] == true)            
    count++;
  if (col < Size - 1 && World[row][col+1] == true)       
    count++;

  return count;
}

I'm really not sure how …

robotnixon 0 Light Poster

Just registered but you guys have been a big help for the whole semester. I have what seems to be a simple problem but I'm just stuck. My assignment is a game of life sim that prompts the user for an input file, and then reads integers from the file that represent coordinates of the cells (row/column). After that, it does its thing until the user decides it should stop. I designed it originally to get the values from the keyboard (enter two integers between 1-20 with a space inbetween until negatives are read) because I thought it would be easy to change my cin's to fin's but I'm having some trouble. As of now, the file seems to open but the grid is blank. Here's the section of relevant code:

int main()
{
    ifstream datafile;
    string filename;
  
  cout << "The input values from the file will begin the first generation." << endl << endl;
  cout << "Follow the prompts to create new generations or terminate the program." << endl << endl;
   
  // Initilize the grid to all dead cells
  bool Grid[Size][Size];
  for (int i=0; i < Size; i++)
    for (int j=0; j < Size; j++)
      Grid[i][j] = false;

  int row, col;

  // Prompt user for filename.
  
    cout << "Please enter the file name containing input values. " << endl; 
    cout << endl;
    cin >> filename;

    cout << fixed << showpoint;

    datafile.open(filename.c_str());
    if (!datafile)
    {
        cout << "File not found" << endl;
        return 1;
    }
    while (datafile)
    {
        datafile …