mrnutty 761 Senior Poster

Confession: I'm at my internship right now, browsing away in the internet

mrnutty 761 Senior Poster

factorial *= (i-1) * i would make the entire factorial zero (or very close to zero) when i == 1.
One way out of this is to start with i == 3.

No because i gets incremented before factorial is computed as a result of the comma operator which declares a sequence point. Thus that for loop is correct.

@OP: also change the type of factorial from double to unsigned int or something similar.

mrnutty 761 Senior Poster

Your factorial is wrong. Since you are updating by 2, you are missing terms in your factorial.

Separate the factorial into its own function. Or do this:

double sineSeries(double x, int n){
	double xPower = 0.0;
	double factorial = 1.0;
	double sineComputed = 0.0;
	bool sign = true;

	for (int i=1; i<=n; i+=2,factorial *= (i-1) * i){
		xPower = pow(x,i);

		if (sign) {
			sineComputed += xPower/factorial;
		}
		else {
			sineComputed -= xPower/factorial;
		}
		sign = !sign;
	}

	return sineComputed;
}
mrnutty 761 Senior Poster

Confession: I love girly songs( don't judge me). Your turn.

mrnutty 761 Senior Poster

Blood, sweat and tears is my choice of drink and a true mans choice as well

mrnutty 761 Senior Poster

Hey all.

When you have the whole program running, and is executed it's running at the black console window. How are the programs made so that they run with GUI interface and stuff like that? Are they exported differently and where are the images and things put together ? Thanks.

First you can't use pure C++ to implement GUI, with that said you can either learn to code GUI using the OS API's or use some well know libraries for GUI.

mrnutty 761 Senior Poster

Hmm, overkill maybe? That whole process can be accomplished with a non-member function, and the approach can be made fully generic (for types that support operator>>) with argument type deduction:

#include <iostream>
#include <istream>
#include <sstream>
#include <string>

template <typename T>
bool get_next(T& value, std::istream& in = std::cin)
{
    std::string line;

    try {
        if (std::getline(in, line)) {
            std::istringstream iss(line);

            if (iss>> value >> std::ws && iss.eof())
                return true;
        }
    } catch (...) {
        // Collect all exceptions into a failure result
    }

    return false;
}

int main()
{
    float num;

    while (!get_next(num))
        std::cerr<<"Invalid input, please try again: ";

    std::cout<<"Your number is "<< num <<'\n';
}

The problem, of course, is your assumption that there's one item of input for each line. You'll find that as you adjust the solution to allow multiple items per line, it begins to look more and more like how the standard library does things. ;)

Yea I know, buts its no fun when the answer is simple :(

mrnutty 761 Senior Poster

OP probably won't understand this completely right now, but just for giggles here is a generic approach-ish.

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


//Used to convert between types
template<typename S,typename T>
struct SStreamConverter{
 S operator()(const T& in)const{ 
    stringstream ss; 
    S ret = S(); 
    if( !( (ss << in) && (ss >> ret) ) ) throw std::exception();
    else return ret;
 }
};

//used to check if a input is a valid type
template<typename T>
struct IsType{
	template<typename InputType>
	bool operator()(const InputType& s)const{
		std::istringstream stream(s);
		T instance;
		return ((stream >> instance) && (stream >> std::ws) && stream.eof());
	}
};

//An exception representing invalid input error
struct InvalidInputException : std::exception{
	InvalidInputException(): std::exception("Error: Invalid input detected")  {}
	InvalidInputException(const std::string& errorMsg): std::exception(errorMsg.c_str()){}
};

//An Input Grabber from the stream
template<typename T,typename Validator = IsType<T>, typename Converter = SStreamConverter<T,std::string> >
class Streamer{
private:
	Validator isValid;
	Converter convertTo;
public:
	//tries to get the input once	
	T get(istream& stream = cin)const{
		std::string input;
		T result = T();
		getline(stream, input );
		//check for valid input
		if(!(isValid(input)) ) throw InvalidInputException();
		try{ result = convertTo(input); }
		catch(std::exception&){ throw InvalidInputException(); }
		return result; //return if everyting if good
	}
	//tries to get the input until a valid once is detected
	T getUntil(const std::string& errorMsg = "Invalid Input detected, try again\n",istream& stream = cin)const{
		T result = T();
		bool validResult = true;
		do{
			try{
				result = get(stream);
				validResult = true;
			}catch(std::exception&){ 
				validResult = false; 
				cout << errorMsg;
			}
		}while(!validResult);
		return result;
	}
};

int main(){
 Streamer<float> streamer; 
 try{
	 float …
mrnutty 761 Senior Poster

I always workout and play basketball. Right now, my goal is to get my body fat percentage under 10%. I need the extra edge for basketball. But I recently started eating salad and chicken for dinner, to avoid carbs as much as I can at night time.

mrnutty 761 Senior Poster

You can't compare character arrays like that. Your best bet is to create a function that will do a loop check of each element in the two arrays. And have it return a boolean.

aka

bool isEqual(char onFile[], char checking[])
{
	for(int i = 0; i < (sizeof(onFile) / sizeof(char)); i++)
	{
		if(onFile[i] != checking[i])
			return false;
	}

	return true;
}

That wont always work like you think it does, specifically, the onFile[] and checking[] gets degraded to a pointer, thus the size information is lost, so you can't use sizeof operator. You should either have a size parameter, or recalculate its size again.

mrnutty 761 Senior Poster

@firstperson

How am I creating my project? I am sorry but what's that question supposed to mean?

You possibly might have created a project with wrong dependencies. When I say create a project, I mean with code blocks. Maybe you have created the wrong type of project. Else you need to manually link the needed headers.

mrnutty 761 Senior Poster

To see if a number is even you can just check the remainder when divided by 2 or check the last bit. For floating number, you can just check the integer part, so there is no need to use fmod since comparing it to 0.0 might not do what you expect everytime.

float f1 = 123.3243f;
cout << (int(f1) % 2 == 0 ? "even" : "odd" ) << endl;
mrnutty 761 Senior Poster

How are you creating your project?

mrnutty 761 Senior Poster

I like firstPerson's idea about rock paper scissors, but seeing as the decisions are totally random and winning is down to pure luck it seems a bit redundant to create an A.I for it.

I beg to differ

mrnutty 761 Senior Poster

You need to apply the following transformation.

1) Remove all nonalpha characters
2) Convert all character to lowercase
3) Compare it to its reverse( or compare begin + i to end - i )

To remove all nonalpha characters to a string you can use the following:

struct IsNotAlpha{
 bool opearator()(const int ch){ return !isalpha(ch); }
};
struct ToLower{
 char operator()(const int ch){ return tolower(ch); }
};
bool isPalin(const std::string& str){
 string res(str);
 //convert all character to lower case
 std::transform( str.begin(), str.end(), res.begin(),ToLower); 
 //erase all character that is not characters
 res.erase(std::remove_if(res.begin(),res.end(),IsNotAlpha), res.end() );
 //compare the string to its transformed reverse
 return str == string(res.rbegin(),res.rend()) ;
}

I'm not sure about it compiling but its just there to give you a general idea.

mrnutty 761 Senior Poster

I don't get you problem, this is what I get for input of 3000.

pppppp   oooooo  w   w   w eeeeeeee rrrrrrr      cccccc   oooooo
p     p o      o w   w   w e        r      r    c      c o      o
p     p o      o w   w   w e        r      r    c        o      o
pppppp  o      o w   w   w eeeeee   rrrrrrr     c        o      o
p       o      o w   w   w e        r      r    c        o      o
p       o      o w   w   w e        r      r    c        o      o...
p       o      o  w w w w  e        r      r    c      c o      o...
p        oooooo    w   w   eeeeeeee r      r     cccccc   oooooo ...

 KW/H Used      Rate    Charge       Tax     Total
      3000     0.001         3      0.15      3.15

all I did was add a cout << endl; in line 23. Isn't that what you expected?

mrnutty 761 Senior Poster

Just learned that you can't use case/switch with strings in C++. So... used if/elseif:

if (theCategory=="colors") getCatArrAndVals(colors);
else if (theCategory == "fruits")  getCatArrAndVals(fruits);
else if (theCategory == "veggies")  getCatArrAndVals(veggies);

If anyone has a sleeker way of doing this, please let me know.

TIA

Sure

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


typedef std::vector<std::string> StringArray;
typedef void(*FuncPtr)(const StringArray& values);


void getCatArrAndVals(const StringArray& values){
 //do something useful
 for(size_t i = 0; i < values.size(); ++i)
	 cout << values[i] << "\n";
}

struct WrappedFunc{
 StringArray savedArg; //argument to be passed to mappedFunc
 FuncPtr mappedFunc; //mappedFunc to be called
 WrappedFunc(){}
 WrappedFunc(const StringArray& arg, const FuncPtr& fp)
 	 : savedArg(arg), mappedFunc(fp){}
 void operator()(){
	 (*mappedFunc)(savedArg);
 }
};

StringArray createFruits(){
	const char* fruits[]={"Apple","Banana","Berry"};
	return StringArray(fruits,fruits + sizeof(fruits)/sizeof(*fruits));
}
StringArray createVegetables(){
	const char* veggies[]={"Asparagus","Bell Pepper", "Carrot","Corn"};
	return StringArray(veggies, veggies + sizeof(veggies)/sizeof(*veggies));
}
int main(){
 typedef std::map<string,WrappedFunc> StringMappedCallback;
 StringMappedCallback callbacks;
 StringArray fruits = createFruits();
 StringArray veggies = createVegetables();
 callbacks["fruits"] = WrappedFunc(fruits,getCatArrAndVals);
 callbacks["veggies"] = WrappedFunc(veggies,getCatArrAndVals);

 string pickedCatagory = "veggies"; //get input from somewhere
 callbacks[pickedCatagory]();
}

Thats the general idea, but of course you would use something like boost::Function adapted to it.

mrnutty 761 Senior Poster

Another simple idea is to make a rock-paper-scissor game. It fits perfectly. There is no optimal algorithm in the sense that it will never lose. But one can code up a learning machine that could find patterns from human inputs and hence try to predict next behavior.

mrnutty 761 Senior Poster

Is this too easy... Looks like the minimax algo more or less achieves perfect play once it plays all the games...

Yea exactly, you don't even have to use minmax, following a simple series of rules can produce unbeatable tic-tac-toe AI.

mrnutty 761 Senior Poster

Thanks, that sure helped me. The code is here for anyone that might want to take a look at it:

int n;
	double sum = 0;
	//promt user to enter the number.
	cin>>n;
    for (int i = 0; i<=n; i++)
    {
    sum+=i;
    }
	cout<<sum <<endl; //demonstrating the result

This gives you the sum of 0 + 1 + 2 + ... + n

You want the sum of 1/1 + 1/2 + 1/3 + ... + 1/n

So instead of each term being i, you need it to be its inverse.

mrnutty 761 Senior Poster

You can use your browser and setup an autofill option, so that when needing to fill out a form, the browser can try to autofill it. Other than that, you need to justify why you would want to do this.

mrnutty 761 Senior Poster

@OP you want this I think:

template<typename R, typename T>
R cast(const T& input){
 stringstream stream;
 stream << input;
 R ret = R();
 stream >> ret;
 return ret;
}
int main(){
 int i = cast<int>("12345");
 float pi = cast<int>("3.1415");
}
mrnutty 761 Senior Poster

You should do something like this :

const string& stringToAvoid = "#\n"; 
string line;
while(getline(cin,line)){
  if(stringToAvoid.find(line[0]) != string::npos) continue;
}

that way you can just add more character to stringToAvoid instead more if's

NathanOliver commented: Nice +9
mrnutty 761 Senior Poster

Thanks so much! Quick and painless! Also, it seems that #include <string> is not needed for the program to run. Is <string> only for some advanced string functions?

include <string> whenever you need to use std::string.

mrnutty 761 Senior Poster

You want ifstream in(foom.c_str());

mrnutty 761 Senior Poster

Your for loop condition is wrong:

for(int i=1;i<=dim1_save;i++){
for (int j=1;j<=dim2_save;j++){

remove that '='

mrnutty 761 Senior Poster

what error? What exactly is the problem you are having?

mrnutty 761 Senior Poster

Use the simplest method until you can prove that it doesn't perform well enough for your needs. A vector of vectors will probably be the simplest, and should also be sufficiently fast, but there's no way of knowing until you've profiled it with a realistic data set.

Although I would like to point out that choosing the correct data structure at the beginning would serve you best, because if you choose the wrong data structure for your problem only to find out at the end after all the performance increase, the data structure wasn't fast enough and now your left with rebuilding it all. But right now a vector of vector of ints would suffice for {-1,0,1} ranged values, or even vector of vector of chars.

What I would suggest for you to do is, use a matrix class that someone already wrote and tested and benched marked, so you don't have to worry about it. Else if you want to create your own, wrap it in some interface, so the public interface won't change, but your lying implementation might, for example you might choose to represent a matrix by a regular 1D array.

mrnutty 761 Senior Poster

Wow are we really having a 4 page long thread about this. I don't get whats the problem. You guys/girls/its needs to get some fresh air and forget this thread ever happened

WaltP commented: Especially since the OP has made 1 single post. +16
mrnutty 761 Senior Poster

If your ultimately wanting to play sound then I would suggest using a library that handles reading and playing sounds for you already. A suggestion would be to use FMOD. Or if you just want to develop on windows then you can use the PlaySound function

mrnutty 761 Senior Poster

I don't see anywhere stated that int main(int argc, char* argv[]) is better than int main() .

I wonder whether char main() is acceptable?

Quoted from wiki-god


C and C++
In C and C++, the function prototype of the main function looks like one of the following:
int main(void)
int main(int argc, char *argv[])

The parameters argc, argument count, and argv, argument vector,[1] respectively give the number and value of the program's command-line arguments. The names of argc and argv may be any valid identifier in C, but it is common convention to use these names. In C++, the names are to be taken literally, and the "void" in the parameter list is to be omitted, if strict conformance is desired.[2] Other platform-dependent formats are also allowed by the C and C++ standards, except that in C++ the return type must stay int; for example, Unix (though not POSIX.1) and Microsoft Windows have a third argument giving the program's environment, otherwise accessible through getenv in stdlib.h:

There was no extra emphasis in the original statement, I just put emphasis on the important statement pertaining to your question.

So both version are valid, neither one is better than the other. Use int main() if you don't need the command line arguments,
or use int main(int argc, char *argv[]) if you do need the command line argument. In C++, if you do need the command line argument, then to conform to standards, you need …

mrnutty 761 Senior Poster

Your user interaction logic would look something like this :

string userInput;
const std::string DONE = "done";
do{
  cout << "Enter a command to call[ add, print, delete, done ] ";
  cin >> userInput;
  if( userInput == "add"){
    /* ask user what to add then add it to the tree */
   }
  else if( userInput == "print") { /* print tree */ }
  else if( userInput == "delete"){ /* ask what to delete, then try to delete it */ }
  else if( userInput == "done"){
     /* save the tree into a file, you can do so by saving each element in the tree into the file */
  }
}while(userInput != DONE );
mrnutty 761 Senior Poster

Its probably not in the namespace, try this :

std::vector< std::string > var;
explicit Term(const std::string&);
mrnutty 761 Senior Poster

Create the following:

1) PredatorModel class
2) PreyModel class
3) MapView
4) PredatorController
5) PreyController

Your PredatorModel will contain all function necessary for a Predator like move, think, kill and so on.
Your PreyModel will contain all function necessary for a Prey like sleep, eat, and so on
Your MapView will be your Map class, this is what will be on the screen. It will show where there are foods, walkable area, prey position and predator position
The Predator and Prey Controller will control how Predator and Prey moves, respectively. They will utilize the interface provided by Predator and Prey class

mrnutty 761 Senior Poster

Are you trying to use STL or not?

If not then all you have to do is include headers

#include <vector>
#include <string>
using namespace std;
int main(){
 vector<string> a;
 vector<double> b;
}
mrnutty 761 Senior Poster

If you are using sdl, then you can use sdl_mixer. But the suggested ones are openAL and FMOD

mrnutty 761 Senior Poster

>>right = past[pastCounter][1]; //When right is ++ or --, if u can m8

That means it increases the position of the snake to the right by one unit

>>past[pastCounter][0]=1;

I have to see in what context it was used, but my guess would be that to start it off an location 1.

mrnutty 761 Senior Poster

You should really use constants like so :

const int COORD_X = 0;
const int COORD_Y = 1;
const int LEFT = 0;
//....

int past[1000][2]; and says that 0 is side, and 1 is up.

Just so we are clear, past[0] should move the snake sideways, that is left and right
and past[1000][1] should move the snake up and down

mrnutty 761 Senior Poster

Yea I believe thats what the author meant, although its not good code.

mrnutty 761 Senior Poster

what do you have now? Post it.

mrnutty 761 Senior Poster

Check if your compiler supports export keyword, although note that its being removed from the standard.

mrnutty 761 Senior Poster

This question is so ambiguous since it doesn't define what an empty array should constitute. One can only guess, smh

mrnutty 761 Senior Poster

> Might I ask for an explanation of this line
> typename std::enable_if< std::is_arithmetic<T>::value, T >::type* = 0 Well, the original question was about

Only valid integer should be returned. All other input should be tossed, user should be asked again for valid integer input.

I took the liberty of generalizing that to 'Only valid number should be returned. All other input should be tossed, user should be asked again for valid numeric input.'. Where the number is any numeric (integral or real) type.

So, the template function

template< typename T = int > T number_from_stdin( ... )

should only be available for numeric types. The last parameter to the function is just a place holder with a default value to ensure that T is a numeric type.

An instance of std::is_arthmetic<T> holds true only if the type T is an arithmetic type (either an integral type or a floating point type). std::is_arithmetic<volatile int>::value is true , so an improved version of the function would be:

template< typename T = int >
T number_from_stdin(  const char* prompt = "enter a valid number, then a <newline>: ",
                      const char* emsg = "error: input is not numeric\n",
                      typename std::enable_if< std::is_arithmetic<T>::value, T >::type* = 0  )
{
    std::string str ;
    std::cout << prompt ;
    if( std::getline( std::cin, str ) )
    {
        std::istringstream stm(str) ;
        [B]typename std::remove_cv<T>::type number ;[/B]
        char trailing_crud ;
        if( ( stm >> number ) && !( stm >> std::ws >> trailing_crud ) ) return number ;
    }
    std::cerr << emsg ; …
mrnutty 761 Senior Poster
if (currentDay = 0)

you want to compare not assign, in another words

if (currentDay == 0)

do that for all of your similar if statements

mrnutty 761 Senior Poster

Your pow function is incorrect. Your first task is to create this function

//returns base^exp in mathematical sense
//example power(2,2) => 4 , power(2,8) => 256
//note works only for exp > 0
int power(const int base,const int exp);

then you can use that power function in your for loop but depending on the sign of the exponent, you can either display the result or 1/result

mrnutty 761 Senior Poster

What exactly are you having a problem with?

mrnutty 761 Senior Poster

Another way using std::vector( not tested nor compiled )

template<typename T>
class Array2D{
public:
 typedef std::vector<T> ColumnVector;
 typedef std::vector<ColumnVector> Array2DType;
private:
 Array2DType _array;
public:
 Array2D(const int rowSize, const int colSize, const int initVal = 0)
 : _array( rowSize, ColumnVector(colSize, initVal ) );

 const T& operator()(const int row, const int col)const{
   return _array[row][col];
 }
 T& operator()(const int row, const int col){
   return _array[row][col];
 }
};

Another way is to simulate 2D array by using 1D.

mrnutty 761 Senior Poster

only mods can close a thread.

Well then I'm asking a mod to close his thread now.

mrnutty 761 Senior Poster

Didn't you start this thread? You can close it any time if the discussion bothers you that much

I can mark it as solved but that won't close the thread. The discussion isn't bothering me, its just getting out of hand. Where is the lock thread button? I fail to see it.

mrnutty 761 Senior Poster

You would have to include that header before you can use it. For example,

//in foo.h
struct Foo{
 //...
};
//main.cpp
#include <iostream>
#include "foo.h"
int main(){
 Foo f;
}