mrnutty 761 Senior Poster

#include<iostream>
#include<windows.h>

int main(){
   string str = "hello";
    cout<<str<<" ";
    Sleep(1000); //wait 1 second
     cout<<"world\n";

 return 0;
}
mrnutty 761 Senior Poster

Garbage in, garbage out. Before you spend a lot of time analyzing your functions to see where the logic error is in calculating the lowest, highest, and average, loop through your array and make sure it's storing what you think it is.

i.e the problem first occurs somewhere in here :

while (grades[pos] != -99)
			{
				grades[pos] = numberOfGrades; // store grade read in to next array location
				pos ++; // increment array index
				cout << "Please input a grade from 1 to 100, (or -99 to stop)" << endl;
				cin >> grades[pos];
			}
mrnutty 761 Senior Poster

Yes. Try declaring a constructor that sends a message when its destroyed
to see how it happens.

mrnutty 761 Senior Poster

what are you trying to do here :

int nuCoins = 50 - (number || randNo);

Do you really mean that nuCoins will only be 49 or 50, provided that both contain some value ( which is your problem by the way, as pointed out ).

mrnutty 761 Senior Poster

>>Hi, from my understanding, if you initialize an object without the "new", it will be only saved in the stack.
Correct, otherwise it would be saved in heap

>>If the method exits, the object is destroyed. Is that correct? What about this code?

Ok lets see,

int main() {
      ///xxx is declared in stack
     //its scope, i.e its lifetime is when the program reaches the 
    //end of this function
	string xxx = getText();  //Look at the function's comment
  
     //thus xxx gets a copy of the string text in getText().
	cout << "from main() " << xxx << endl;
}
 
string getText() {
     //text is declared on stack
    //its lifetime or scope is when the program reaches the 
    //end of this function
	string text("Hello World!"); 
	cout << "from getText() " << text << endl;
	return text; //returns a COPY of text
}

>>In getText() method, I created a string without the "new", so I assumed that the string will be destroyed after the return.
Yep, its destructor is called.

>> But why does xxx in main() equal to the return of the getText() method? Should it be that xxx contain an unknown value since the object it points to was destroyed? Thanks a lot!

What happens with your functions is that getTex() is called first,
the inside that function you create a string object, and do some
stuff and at last you return the string object. When you return the string object, …

mrnutty 761 Senior Poster
#include <iostream>
 
int main(void) {
char c, d=10;
while( std::cin.get(c) &&  //while cin does not fail to get input
        (c!='2' || d!='4') &&  //while c != '2' or d != '4'
        std::cout.put(d)  //while cout does not fail to write
        )
       d=c; //save last input
}

so basically when the user inputs a number , it gets saved into d,
and when the user input another number, it checks if that number is 2 and if the previously saved number was 4. if so then it quite, otherwise it continues.

mrnutty 761 Senior Poster

Hi this is the code for life, universe and everything problem, where the program stops only when the user inputs the number "42"

I tried to understand the problem, but could not make it that how the program stops at exactly 42. Any help would be extremely appreciated.

#include <iostream>
 
int main(void) {
char c, d=10;
while(std::cin.get(c) && (c!='2' || d!='4') && std::cout.put(d))
d=c;
}

Forget that "ugly code".

This does the same and is more readable :

#include<iostream>

int main()
{
  //enable less qualified name
   using std::cout;
   using std::cin;
   using std::endl;

   int terminateNumber = 42;
   int inputNumber = -1;

  while( inputNumber != terminateNumber )
  {
      cout <<" Enter a number : " ;
      cin >> inputNumber;
      cout<<"\nYour number is : " << inputNumber << endl;
      cout << endl;
   }
  
   return 0;
}

It hasn't been compiled though.

mrnutty 761 Senior Poster

try posting your whole code

mrnutty 761 Senior Poster

Haven't tested it yet, but it could be similar to this :

int M = 5;
int i = 1;
while(i <= M) cout << i++ <<" ";  //print from 1 to 5
while(--i > 0) cout << i << " "; //print from 4 to 1
mrnutty 761 Senior Poster

I think you want it to be this :

static float calcTaxes(float grossPay)
{
float netPay ; 

if (grossPay <= 300)
netPay = (float) (grossPay - (grossPay * 0.15));

if (grossPay <= 450)
netPay = (float)(grossPay - (grossPay * 0.20));

else if (grossPay > 450)
netPay = (float)(grossPay - (grossPay * 0.25));

return netPay
}

You forgot to set the return type of the function as well as returning a value.

mrnutty 761 Senior Poster

How about you just ask your teacher since it will be easier and more straight forward.

mrnutty 761 Senior Poster

Easy way out, just put a condition to check if "i" is at .size() - 1;
if not then print or else not print.

mrnutty 761 Senior Poster

you already have a non negative checker there :

if (num < 1 || num > 4)

just change it to :

while (num < 1 || num > 4){
cout<<"Invalid choice\n";
cin >> num;
}

And the rest after that, the else if(num == 1 || num < 0 { ... }
is not needed.

mrnutty 761 Senior Poster
int Num  = -1;
cin >> Num; //get input

while( Num < 0 ) //while input is less than 0 or negative
{
    cout <<" Enter a positive number  : ";
    cin >> Num;
}
mrnutty 761 Senior Poster
strcpy (i->info.c_str(), newNode->info.c_str()); // copy i's info into newNode
i->link = newNode;

strcpy takes in c style string.

mrnutty 761 Senior Poster

I won't even say anything. Just, Here :

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

int main()
{

cout << "This is a template.\n";
cin.get();
return 0;
}
mrnutty 761 Senior Poster

How about you explain this code. Tell me what each line does.
Then tell me what you think you need to do in order to duplicate a word.

void duplicateWords (nodeType*& first, nodeType*& last)
{
 
struct nodeType *i;
int wordCount = 0;
 
for (i = first; i->link != NULL; i = i->link)
{
char temporaryWord[3];
 
if (i->link->info == temporaryWord[i])
 
wordCount++;      
}    
 
 
}
mrnutty 761 Senior Poster

Try this. And inline won't do anything helpful by the way.

ostream& operator << (ostream& os, FixedSizeMatrix& obj)
{
   obj.print(os);
   return os;
}
mrnutty 761 Senior Poster

This is great, but how would I go about preventing duplicates when the array is randomized?

You could sort it and then check if the next element is the same and
work from there.

mrnutty 761 Senior Poster

This was was not working for me.

It works for me :

import java.*;


class Main
{
    static void Print(Object ob){
        System.out.print(ob);
    }
    static void Print() {
        System.out.println();
    }
    public static void main(String[] Arg)
    {
        final int ROW = 5;
        final int COL = 5;
        
        char[] fake2D = new char[ROW*COL];

        for(int i = 0; i < ROW*COL; i++)
            fake2D[i] = (char)('A' + i);

        for(int i = 0; i < ROW; i++)
        {
            for(int j = 0; j < COL; j++)
            {
                if(i > 0 && i % ROW == 0)
                    Print();

                Print(fake2D[j + i * ROW] + " ");
            }

            Print();
        }

    }

}
mrnutty 761 Senior Poster

In this there is restriction that the array dimension can't be prime

Why is that again?

mrnutty 761 Senior Poster

Can you post your whole code if its not too big.

mrnutty 761 Senior Poster

Normally with destructor and constructor,
you should do something like ,

Array(){
  mainArray = new Type[0];
}
~Array(){
  delete [] mainArray;
}

Here is a complete example.

#include <iostream>
#include <string> 
 
using std::cout;
using std::string;
using std::endl;

template<typename Type>
class Array
{
	typedef unsigned int uInt;
private:
	uInt len;
	Type * mainArray;
public:
	Array(){
		mainArray = new Type[0];
		len = 0;
	}
	Array(uInt Sz, Type val){
		mainArray = new Type[Sz];
		len = Sz;
		for(uInt i = 0; i < Sz; i++)
			mainArray[i] = val;
	}
	~Array(){
		//Its able to delete a null pointer, i.e if(len == 0);
		delete [] mainArray; 
	}
	bool isEmpty() {
		return len == 0; 
	}
	uInt Size(){
		return len; 
	}
	bool Print(int col)
	{
		if(!len) 
			return false;

		for(uInt i = 0; i < len; i++) {
			if(i && i % col == 0) 
				cout << endl;			
			cout<<mainArray[i]<<" ";
		}
		
		return true;
	}
	
};

int main()
{  
	Array<int> Numbers;
	Array<float> Numerics(12,10);

	cout<<"Numbers size is : " << Numbers.Size() << endl;
	cout<<"Numerics size is: "<< Numerics.Size() << endl;
	
	if(Numbers.Print(4))
		;
	else cout<<"Nothing to print in Numbers\n";

	cout<<endl;

	if(Numerics.Print(4))
		;
	else cout<<"Nothing to print in Numerics\n";
	
	cout<<"\n\n";


	return 0;
}
mrnutty 761 Senior Poster

" I was using the class in a program with a self-written form of Vector, and it kept crashing upon destruction of the object."

Mind showing your constructor and destructor?

mrnutty 761 Senior Poster

The proper use of delete and delete []

int *Num = new int;
int *Array = new int[5];

delete Num; //good
delete [] Num; //Bad -- undefined 
delete [] Array; //good
delete Array; //bad --undefined

As you can see, you have :

Category* pCat = new Category;

Which should follow up with a

delete pCat;

You are using an array notation bracket, i.e [] on pCat, and that
is probably why it lead you to think you should use delete [] pCat,
but in fact, if you know abut pointers, pCat[0] is the same as *pCat.

Also (1) pCat[0].GetType() is the same as (2) (*pCat).GetType and (3) pCat->GetType.
Use the option (3), as it is more clear, that pCat is not an array of a class object and "prettier."

mrnutty 761 Senior Poster

Yes. In fact thats very common, using 1d array as a mimic of a 2d.

final int ROW = 5;
final int COL  = 5

char[] Letters = new char[ ROW * COL];

for(int i = 0; i < ROW * COL; i++)
    Letters[i] = (char)( 'A' + i );

for(int i = 0; i < ROW; i++)
{
   for(int j = 0; j < COL; j++)
   {
       System.out.print( Letters[j + i * ROW] + " " );
   }
}

It hasn't been tested, but you should get the idea, if it doesn't work.

mrnutty 761 Senior Poster

It seems like you are trying to make a code to send somebody a
harmful .exe.

Therefore I will not tell you.

If i am wrong then say so, trusting you not to lie.

tomtetlaw commented: Good Thinking :) +0
mrnutty 761 Senior Poster
#include<iostream>
using namespace std;

int main()

{
    char name[10]= ""; // empty string
    int counter = -1;
    
	while (strcmp(name, "stop") != 0)
	{
		cout<<"Enter your friend's name (""stop"" to quit): ";
		cin>>name;
		counter++;
	}
	if (counter == 0)
	{
		cout<<"Go Make some friends you emotional loser!\n";
	}
	else
	{
		cout << "Congratulations you have " << counter << " friends!!\n";
	}
	system("pause");
	return 0;
}

My list of question :

1) WHY ?
2) What happens when a name is longer than 9 characters ?
3) Is it easier ?
4) Less code ?
5) Better looking ?
6) more understandable ?
7) Less prone to bugs ?

Additional details :

It needs to use <cstring> library for it to be able to use strcmp(...).

This code :

if(counter == 0)

is the same as

if(!counter);

So, there is no need to use the boolean compare operator when
a "not" can do the job.

mrnutty 761 Senior Poster

You know using sstream is a lot easier :

#include<iostream>
#include<sstream>

using namespace std;

int main()
{ 
	
	
	int NumberToReverse = 123456;
	
	string str = "";

	stringstream sstrm;

	sstrm << NumberToReverse;

	sstrm >> str; //str = "123456";

	int i = str.length() - 1;
	
	cout<<NumberToReverse <<" reversed is : ";
	
	for( i; i  >= 0; --i)
		cout<<str[i];
	
	cout<<endl;


	return 0;

}
mrnutty 761 Senior Poster

Something like this ? :

#include <iostream>
#include <vector>
#include <string>

using std::string;
using std::cout;
using std::endl;
using std::cin;

class RationalNumbers
{
private:
	float Numerator ;
	float Denominator ;
public :
	RationalNumbers() { }

	template<typename T>
	RationalNumbers(const T& RationalNumbers);
};
template<typename T>
RationalNumbers::RationalNumbers(const T& var){
	cout<<typeid(T).name()<<" specialized\n";
}
template<>
RationalNumbers::RationalNumbers(const int& var){
	cout<<"Int specialized\n";
}
template<>
RationalNumbers::RationalNumbers(const float& var){
	cout<<"Float specialized\n";
}
int main()
{ 
	 		
	float A = 4.2f;
	int B = 2;
	char C = 'a';
	string str;

	RationalNumbers R1(A);
	RationalNumbers R2(B);
	RationalNumbers R3(C);
	RationalNumbers R4(str);

	return 0;

}

denominator

mrnutty 761 Senior Poster

Before fixing your code, you should fix your grammar.

mrnutty 761 Senior Poster

hey can u pls edit in my program bcz i m really afraid tht i might mess up d whole program...it already took me too long to write the program...thank u n i appreciate ur help

Then copy and paste it into a text file, and save it. Then start playing around with it. If you mess up too much, then just copy and paste the
original content from the text file.

mrnutty 761 Senior Poster

Example :

#include <iostream>

using namespace std;

int main()
{
   int val[4] = {1,2,3,4};

   int limit = 2;

   for(int i = 0; i < limit; i++)
     {
         cout<<"Enter value : ";
         cin >> val[i]
      }
   return 0;
}
mrnutty 761 Senior Poster

I am guessing you are a senior in high school.

Beginning, you will take course such as :

calculus, physics, chemistry, cse101(intro to programming, language depends), and some general education class, maybe history.

The as time goes on, you will get more into the programming areas.

The school should provide you with a curriculum list, that shows which
class you have to take, in order to get a Comp.E degree.

mrnutty 761 Senior Poster

Haven't used it for a while, but I think it takes the ascii value in int form.

if you wan't to use variable use a char variable

char print ='0';
for(print = '0'; print != '9'; print++)
  glutStrokeCharacter(GLUT_STROKE_MONO_ROMAN, print);

Also google the function, and you get a documentation, like this

mrnutty 761 Senior Poster

yes sure you can. For example you might have a reset method that
resets everything to a default constructor :

class A
{
    int c;
    public : 
   A() { c = 1000; }
    A(int x ) { c = x; }
     void reset() { *this = A(0); }     
};
mrnutty 761 Senior Poster

You're thinking too hard.

string src = "hello"
for(int i = src.length()-1; i >= 0; i--)
      cout<<src[i];
mrnutty 761 Senior Poster

Yes, use template.

You could use template specialization, to make sure that the template
parameters is a number.

Here is a way to do that :

#include <iostream>

using namespace std;


template<typename Type>
struct is_numeric { static const int i = 0; };

//Template specilization
template<> struct is_numeric<short>				{ static const int i = 1; };
template<> struct is_numeric<unsigned short>	{ static const int i = 1; };
template<> struct is_numeric<int>				{ static const int i = 1; };
template<> struct is_numeric<unsigned int>		{ static const int i = 1; };
template<> struct is_numeric<long>				{ static const int i = 1; };
template<> struct is_numeric<unsigned long>		{ static const int i = 1; };
template<> struct is_numeric<float>				{ static const int i = 1; };
template<> struct is_numeric<double>			{ static const int i = 1; };
template<> struct is_numeric<long double>		{ static const int i = 1; };

template<typename Type>
class Numeric
{	
	//Check is Type is numeric
	int AssertType[is_numeric<Type>::i];

	Type * Vector_;
	unsigned int length;
public:
	Numeric()	{ Vector_ = new Type[0]; };
	~Numeric()  { delete [] Vector_; }
};

int main()
{ 
	Numeric<int> a;
	Numeric<float> b;
	Numeric<unsigned short> c;
	Numeric<string> d; //Error  
	Numeric<char> e; //Error  
	

	return 0;

}
StuXYZ commented: Nice, easy to understand template traits example +6
mrnutty 761 Senior Poster

Flawed and bigger :( you win.

You learn from mistakes.

mrnutty 761 Senior Poster
#include <iostream>
#include <cmath>
using namespace std;

bool isPrime(int x)
{
	if( x == 1 )
		return false;
	if( x % 2 == 0 && x != 2 )
		return false;
	if( x % 3 == 0 && x != 3 )
		return false;
	if( x % 5 == 0 && x != 5 )
		return false;
	if( x % 7 == 0 && x != 7 )
		return false;
	return true;
}

bool is_prime(int i)
{
	if(i < 2) return false;

	if(i == 2) return true;


	float half = ceil( sqrt((float(i))) ) + 1;

	for(int j = 2; j < half; j++)
		if(i % j == 0) return false;

	return true;
}
int main()
{
	int i = 0;

	cout << boolalpha;

	while(true)
	{
		if(isPrime(i) != is_prime(i))
		{
			cout<<"When your function versus my simple brute force disagrees : \n\n";

			cout<<"Result :  from your function : "<<i<<" is prime = "<<isPrime(i)<<endl;
			cout<<"Result :  from my function   : "<<i<<" is prime = "<<is_prime(i)<<endl;
			cout<<"\nCheck what google says\n\n";
			cin.get();  
			break;
		}
		i++;
	}
	
	return 0;
}
mrnutty 761 Senior Poster

Fail.

mrnutty 761 Senior Poster

simplify.

1) Make a bool function that takes a int i as a parameter and checks if it is a prime or not.
2) inside your loop, check if i to MAX is a prime.

your function prototype might look like this :

bool isPrime(int num);

HINTS :
a) How do you when a number is a prime ?
- When it is only evenly divisible by itself an 1.
b) Use the mod operator.

mrnutty 761 Senior Poster

You can't do this :

int a;
cin >> a;
string str[a]; //error a is not const
mrnutty 761 Senior Poster

your haven't initialized the variable "a". And it has to be const, when using it to determine the size of an array.

const int A = 10;
string str[A]; //good
int b = 3;
string str[b]; //error
mrnutty 761 Senior Poster

I cant take const out. The teacher wants us to us his function and develop our code around it.

Well there is const_cast but generally, you shouldn't have to do this.

mrnutty 761 Senior Poster

This would also work with recursion :

void Pattern(int Row, int Left = 0)
{
	int Right = Row - Left - 1;

	const static int Mid = (Right + Left) / 2;

	if(Left > Right ) return;

	for(int i = 0; i < Row; i++)
	{
		if(i == Left) 
			cout<<"^"<<" ";
		else if(i == Mid)
			cout<<"^"<<" ";
		else if(i == Right)
			cout<<"^"<<" ";
		else cout<<"*"<<" ";
	}

	cout<<endl;;

	Pattern(Row,Left+1);
}
mrnutty 761 Senior Poster

the cctype header has a function called isdigits(...). You can use that
to validate whether a string contains integer. There are also isspace(..)
among other things in that library. Check out the library , here
Here is an example :

#include<iostream>
#include<cctype>

using namespace std;

int main()
{
	string phoneNumber = "777777777";

	bool pass = true;

	for(int i = 0; i < phoneNumber.size(); i++)
	{
		if( isdigit(phoneNumber[i]) )
			pass = true;
		else
		{
			pass = false;
			break;
		}
	}
	
}
mrnutty 761 Senior Poster

Here is your code indented with code tags.

One problem with your function is that you never declared s1 and s2.

Below code fixes that :

#include <iostream>
using namespace std;

void drawShape(int nrP)
{
	int s1 = 0,s2 = 0;  //(NEW)

	for (int i = 1; i <= nrP; i++)
	{
		s1 = i - 1;
		s2 = (2 * nrP - 2 * i - 1); 
	
		for (int j = 1; j <= s1; j++)
			cout << '^';
		
		cout << '#';
	
		for (int j = 1; j <= s2; j++)
			cout << '^';
	
		cout << '#';

		for (int j = 1; j <= s1; j++)
			cout << '^';
	
		cout << endl;
	} 
}

int main()
{
       int nr = 0;

	cout << "Number of rows: ";
	cin >> nr;
	drawShape(nr);

return 0;
}
mrnutty 761 Senior Poster

portability :

"The actual type of size_t is platform-dependent; a common mistake is
to assume size_t is the same as unsigned int, which can lead to
programming errors, particularly as 64-bit architectures become more
prevalent"

KonkaNok commented: ..just what I was looking for. +1
mrnutty 761 Senior Poster

The unnamed fields may just be padding so that the structure's data is laid out correctly...Gerard4143

Yes, structure goes by units of 4.