csurfer 422 Posting Pro

You haven't even tried to overload + and - operator. First read about it,try it and come back to us with errors or bugs,then we will help you. And next time put your code inside code tags.

P.S : We are not a bunch of jobless people.

csurfer 422 Posting Pro

I told you not to delete the contents of the file thats it. But I didn't suggest to remove infile.clear() because its use here is to reset all the flags related to ifstream.
Therefore:

infile.clear();
infile.seekg(0,ios::beg);

Will do your work.

And also you haven't corrected this:

// store numbers in an array
for ( int i = 0; i <= sequence_length; i++)
{
infile >> x;
number_array = x;
}

It should just be < not <=.

csurfer 422 Posting Pro

Its better if you post the code which you have tried so that we can believe you have actually worked on it.But you have asked just for the algorithm here you have.

1)Run outer loop (say for loop) n number of times where in n=number of lines.
2)Assume a variable no_of_asterisks which holds 2 initially.(Because you are starting with printing two asterisks)
3)Within the loop stated in (1) write another loop which loops no_of_asterisks number of times and prints a asterisk in every loop.
4)After step (3) go to a new line and then increment the value of no_of_asterisk variable to the value you want to increment it with(here say +2).

Keep on looping this.

Salem commented: Well put. +33
csurfer 422 Posting Pro

To check the length of file you have done

while(infile) {
		infile >> x;
		sequence_length++;
         }

After this the file pointer is at the end of file now you need to re-assign the pointer to the start of file.So before taking array input do

infile.seekg(0,ios::beg);

And then take the input into the array. And ya do not clear the file because you cannot fetch values into the array if you do so.

And also make following changes :

int sequence_length = -1;
// store numbers in an array
for ( int i = 0; i < sequence_length; i++)
{
	infile >> x;
	number_array[i] = x;
}
csurfer 422 Posting Pro

I can see what your saying, but id really have no idea how to implement it. do you think it would be possible to simulate a file within a file? and have my program recognise when to stop reading from it?

By your previous posts its clear that you can group your data,that means your data is divided in some form of units say block of data.Just spend some time analyzing this block and you will find a data within it which is unique to it.Mark this as key and make effective use of it,like an identity to the whole record.
In the index file just hold these keys and the positions in which corresponding block is stored in main file (use seekg to find position).
With the above information add two things 1)Your time in studying the concepts 2)Your coding creativity and you are done. :)

csurfer 422 Posting Pro

Or may be a priority array which stores the data in the node for referencing the node and its level or priority in the tree.

csurfer 422 Posting Pro

i want my program to pull out very specific small strings from files, but i dont know whats the best way of going about this. ive written a function that can get a specific line from a file, but its hard to keep track of where relevant data is. ive started to store different types of files in different directories, but i dont want to have too many, especially when the files are so small.

Well you can maintain an index file which holds the indexes where in the key is the type of record and the key value is the position of the record in the record file.In this way you will limit the number of files to just two,one with the data and another with the index.

csurfer 422 Posting Pro

After the end of file,the file is filled with null characters,so if you move the file pointer to a far off place and get a line from there then it inputs several '\0' characters into your string which when output by << doesn't show anything.

NULL is a macro for (void *)0 called null pointer and its completely different from '\0' which is null character with ascii value 0.

csurfer 422 Posting Pro

Try to clear the contents of the stream at strategic points. Read more on "flushing the standard input stream in c". :)

You can code the getans() function in a far better way.

And asking you out of curiosity "Being a newbie how did you know it was taking 10 as the input? Because as far as I have seen your program you are never printing the decimal(ascii)value of char variable ans at any point.":?:

csurfer 422 Posting Pro

Attachment point theory is good.You can create a board in which you assign three different symbols which mean <a char is placed here>,<a char can be placed here>,<a char is not placed but you cannot place a character here.>

And for the question you have asked what you can do is take the character's you have (the ones which you can make words) into an array and try rearranging them so that they form some meaning,in the process consider the attachment points as the starting character.That is even though you have 7 character blocks try using the 8th block as one of the available characters. In this way by arrays you can control the number of times you use a character.

csurfer 422 Posting Pro

Ya sorry miss typing : ;)

Here is the errata

A * 16^2 + B * 16^1 + C * 16^0 i,e
10 * 256 + 11 * 16 + 12 * 1
2748

Ya pairing system works only on powers of two where pairs of x digits are made to find value in base n system when binary is given where 2^x=n.

Every thing else is correct !!! :)

csurfer 422 Posting Pro

It would be better if you divide that nary tree nodes in some hierarchical levels so that it would be helpful in deciding their positions in future.

csurfer 422 Posting Pro

Does no one read the forum rules ??? At least a glance ??? Please go through this once.Use Code Tags.

And Please Use English here.This is not a mobile chat zone.

Your mistakes :

cout<< (rand() % 10) + 1<< " "; //creates random numbers from 1 to 100

How can you expect the above code to generate random numbers till hundred ? It can generate only until 10.

I really had a hard time understanding what you want and I still am not able to get what you really want to do.

Your statement has something about reorganization and you are using cout.Once you output to the console then how can you even organize it?
Use an array or something to feed in the random generated numbers and also user input numbers and then use some sorting algorithm if your objective is just to arrange the numbers.

csurfer 422 Posting Pro

Spacebar is most used in my computer.Poor thing gets all my trashing (only key with two finger access).Both my thumbs just pounce on it.;)

Unused key : Default windows key !!! :)

csurfer 422 Posting Pro

This is one classical example of recursion. I hope you know the rules of this problem.

Here you have three stands say a b c where where n pegs are inserted into a from 1 to n numbering where 1 is on top and 2 below it 3 below 2 and likewise to n.
Rule is larger number cannot come over smaller number and you need to get all pegs in same order finally to stand c or 3 as per your program.

Program :
In it you are calling a recursive function towers which has number of pegs left to move source and destination stands using an intermediate stand.

if(numToMove == 1)
{
cout << initialPeg << "->" << finalPeg << endl;
}

here you say if there is only one peg then move it from stand one to stand three directly objective attained.

else if(numToMove > 1)
{
Towers(numToMove - 1, initialPeg, holdingPeg, finalPeg); // 1, 2, 3
cout << initialPeg << "->" << finalPeg << endl;
Towers(numToMove - 1, holdingPeg, finalPeg, initialPeg); // 3, 2, 1
}

Here you say that if its more than one peg to move assume the problem is just for actual - 1 number of pegs and solve it.

That is if you can't solve for 5 pegs solve for 4 pegs and then for five similarly all conditions narrow down to just one which is always solvable.

You have the best …

csurfer 422 Posting Pro

@Ancient Dragon

*p2 = 0;

Hey shouldn't the above code be

*p2 = '\0';

more precisely to signify null character even though both lead to ascii zero itself.

And you normally avoid typecasting of malloc right ? Any special purpose here ?

csurfer 422 Posting Pro

Here is a guide to convert decimal to binary in detail.Try this.
Apply the same theory for octal (use 8 to divide decimal numbers) and hexadecimal (use 16).Or

Once you have binary number say 10011011 its really easy to convert it into any form.
Say octal pair three digits from right to left
(when short of digits use 0's):
010 011 011
2 3 3

Say hex pair four digits right to left :
(when short of digits use 0's)
1001 1011
9 B

csurfer 422 Posting Pro

Hey its quite easy , 0x is hex right then ABC is calculated as follows :
A * 16^2 + B * 16^1 + C * 16^0 i,e
10 * 484 + 11 * 16 + 12 * 1
2748

csurfer 422 Posting Pro

No, at least not for the purpose of his assignment. He is probably learning about character arrays, not c++ STL classes.

May be you are right Ancient Dragon (you always are :))but he has just concentrated his attention on strings only and never mentioned strings as character array so I thought giving this information would be fruitful and Dani is also about providing better ways right?

csurfer 422 Posting Pro

Can I look at the module which generated this error I mean just that function.

csurfer 422 Posting Pro

Oh sorry about those words "URGENT" and "IMPORTANT"
but i am a new member to this website and I am a new student studying in C++. Thanks for letting me know so next time I will not use them.

Read the posted letters properly atleast, VERNON took the trouble of letting you know how exactly you need to put c++ code tags and still you have put it within quotes. :(

Reply :
For the statistics function (going by word statistics) you can move all the records entered into a file and make way to display the file when asked for the statistics.Using simple file handling functions you can achieve this.

csurfer 422 Posting Pro

Thanks for the threads ! It feels just like coming back home where we actually started ! :)

csurfer 422 Posting Pro

Wow !!! asking source code in Dani directly and that too at two places. I am SHOCKED !!!

csurfer 422 Posting Pro

Don't Shout !!! Writing things in capital letters is regarded as shouting...! So don't use it. And it may be urgent for you not for us so have patience. And indent the codes and use code tags.

Salem commented: Well said! +33
Intrade commented: Aye =p +1
csurfer 422 Posting Pro

Well the objective is just to compare two strings right? Then even though strcmp can do the work wouldn't the usage as

#include<string>
using namespace std;
//within main
string str1 str2;
//inputs to strings as cin<<string
if(str1==str2)//comparision

Wouldn't the above implementation be more efficient? As we are using standard namespace.

>San you can go through this.

P.S: Guys the person "san gabriel" doesn't know about string classes I suppose may be new to c++ so wouldn't the new info be better?

csurfer 422 Posting Pro

Good work !!! But file access every time can be time taking,so,may be you can implement a sudoku board with linked list or a hash table so that traversal can get faster.

csurfer 422 Posting Pro
global_procedure Root (
	alters Natural_Power_2& n,
	preserves Integer r
    );
    /*!
	requires
	    r > 0
	ensures
	    n^(r) <= #n < (n+1)^(r)
    !*/

//--------------------------------------------------------------

procedure_body Root (
	alters Natural_Power_2& n,
	preserves Integer r
    )
{
    
  // need to fill
   

}

there is the code i have so far.... i need to fill procedure body... any idea?

What you have posted is a pseudocode with two C function declarations and we asked for the code which you have tried ok. Don't do the cut and paste job here.We helping you here are not dumb to think above thing as a code.So if you want answers and help give an understandable description of your question and the code which you have tried...

csurfer 422 Posting Pro

Its better not to paste the questions given in other portals for you to solve here for us to solve. But since you have tried to code this is my view...

>You are trying to find out factors of 2 and 5 for every number within a limit "num" for this you are calling two functions five() and two() for every num starting from 1 and ending at num.
>Instead try finding the factors for factorial itself,in this way you will call those functions only once for every factorial and multiplication would take minimum time when compared to function call for every number.

csurfer 422 Posting Pro

Qn 1.

Write a C++ program that creates appropriate
variables and performs the following actions:
Gets the user to enter their name and year of birth.
Adds the users names to one of two text files “wise.txt”
or “strong.txt” based on their age at the start of this year.
To be considered wise the user must have been over 21
at the beginning of this year.

>Take variables for name(string type) date<day/month/year>(integer type) use cin to take inputs.Here is some help
>Get system date and find out what was user's age at the year start.You can try this help,but better resort to simpler means at first.
>Check if the user's age is greater than 21 and then use fstream pointers and use then to write within your required file.

>>In total go through this once.

csurfer 422 Posting Pro

iamthwee is right but if the intention of your tutor is to make you try such things by using programming constructs then you may try using linked list to solve your problem.

csurfer 422 Posting Pro

Well if you are using linux then you can always use the meta-characters and the od command to your requirements.Check these out <1> <2>

csurfer 422 Posting Pro

Read Ancient Dragons post again.

Problems: the close parentheses is missing :-p

You won't get the required output because strtok uses the character within " " in strtok(str," ") as the delimiter and uses it to cut the string rather than including it.This explains why the closing paranthesis is missing.

One silly but quick correction you can do is this :

tokenPtr = strtok( sentence, ")" );
cout << tokenPtr << ')' << '\n';
tokenPtr = strtok( NULL, "-" );
while ( tokenPtr != NULL )
{
       	cout << tokenPtr << '\n';
        tokenPtr = strtok( NULL, "-" );
}
csurfer 422 Posting Pro

Explain your needs properly and paste in the code which you have tried.

csurfer 422 Posting Pro

Well your question is not quite clear but you can always use fopen command with :
“rb” Open a binary file for reading
“wb” Create a binary file for writing
“ab” Append to a binary file
“rb+“ Open a binary file for read/write
“wb+“ Create a binary file for read/write
“ab+“ Open a binary file for read/write

as modes to manipulate it.For more info try this.

csurfer 422 Posting Pro

Don't pin in the whole code every time.Just extract the erroneous part,that way you too will dive deeper into the code and easy for us to analyze too

csurfer 422 Posting Pro

"Please don't kill the codes,Pay them some respect "
After all,they are "your" codes:

for(i=0;i {
tot[i]=0.40*Assignment_average[i]+ Quiz_Average[i]*0.15+ participation[i]*0.10+Midterm[i]*0.15+ final[i]*0.20  avr[i]=tot[i]*100;
 }

Complete their format at least....

Errors:
>Usage of "&menu" in printf is not only syntactically wrong but also useless.Why do you want to print value of menu there???

>The code :

printf("Input a Name! =");
  scanf("%s",&name[i]);

is incorrect usage.If you want to pick the i th name then

scanf("%s",name[i]);

is enough as per your declaration of name array.

csurfer 422 Posting Pro

Your program may be right and giving the right output too but try to use the inbuilt "C" functionality more.Because even after using recursion if you are doing so much work its nothing but "Crime Against Recursion".Try this...

#include<stdio.h>
#include<string.h>
#define MAXSIZE 10
void display(char c,int cnt,int i,char num[],int pos[])
{
     char temp;
     temp=num[pos[i]];
     num[pos[i]]=c;
     if(cnt-1!=0)
     {
               display('0',cnt-1,i+1,num,pos);
               display('1',cnt-1,i+1,num,pos);
     } 
     else printf("\n%s",num);
     num[pos[i]]=temp;
}         

int main(void)
{
    int i,j,nox=0,pos[MAXSIZE];
    char num[MAXSIZE];
    printf("Enter Binary Number : ");
    scanf("%s",num);
    for(i=0;i<strlen(num);i++) 
               if(num[i]=='x')nox++;
    if(nox!=0)
    {
              for(i=0,j=0;i<strlen(num);i++) 
                                if(num[i]=='x')pos[j++]=i;
              display('0',nox,0,num,pos);
              display('1',nox,0,num,pos);
    }
    else printf("%s",num);
    return 0;
}

P.S : Usage of functions is recommended only when a set of instructions are used again and again,to increase readability and to reduce error.Their usage for just two lines of codes as in this function just increases the compile time and gives no noticeable benefit.

csurfer 422 Posting Pro

You can create a new program for it where in you can declare a character array

char file[<file_size you want to set>];

Read in the file into this array,so you are limiting the size of it,then delete the contents of the file and write the contents of the array back to the file.

csurfer 422 Posting Pro

Well I really couldn't get what you meant but I will answer to the point I think you asked...k

Well you can allocate two dimensional array as follows:

char **array; //Your two dimensional array
int str_nos=10; //No of strings you want to have
int str_len=60; //Maximum length of each string
array=malloc( str_nos * sizeof(char *) );
//Above st allocates memory for no of char pointers or strings
for(i=0;i<str_nos;i++)
{
a[i]=malloc( str_len * sizeof(char *) );
}

In this way you can dynamically allocate the number of strings and also their lengths by just altering he str_nos and str_len .I hope this helps :)

csurfer 422 Posting Pro

Ancient Dragon has always got some great methods which come handy :) the above post by him is just superb. And ya if you want some predefined words as your file names for example in a business file like FINANCIAL, STRATEGIC and all you can feed it in the array defined as

char array[100][255];

and access it as

FILE *fp;
for(i=0;<n;i++)
{
fp=fopen(array[i],"w");
//your code
}
csurfer 422 Posting Pro

Hey definition of a struct doesn't create struct objects for you to play around as variables of data type struct.

You need to create the objects of that struct to access memory and do other assignment stuff. So try this:

int main()
{
TransistorRec a;
printf("Enter manufacturer's ID, polarity, power, gain, stock ");

//And access the object as follows...

scanf("%c %c %f %f %i",a.manufacturersID[0],a.polarity[0],a.power[0],a.gain[0],a.stock[0]);

I hope you got the difference between defining a struct and creating an object of that struct type. One thing to know is only objects are allocated memory and not the definition of struct. And so only objects come in handy.Enjoy coding... :)

csurfer 422 Posting Pro

This is where you went wrong.

In your program pointers min and max are there but are not pointing to any memory space at all.So when you try to access some memory as *min or *max they try to refer a memory not been allocated hence segmentation fault core dumped.

Try this:

int main( int argc, char *argv[] ){

int *numberlist, i, n, *min, *max ,minimum,maximum;

min=&minimum;
max=&maximum;
//Followed by your code

By this you will have allocated the memory and then accessing it so no problem. And ya your max and min values will be in maximum and minimum.

csurfer 422 Posting Pro

Being in this community for a while you very well know our answer "You are in a hurry solve it yourself" So stop posting "do quickly" and all from next time because we are here to learn and not take orders...

As for your answer choose any problem in which various choices are involved.You may also present your paper on the basic working of switch itself.Its a great thing to present.Refer this.

Aia commented: :) +14
csurfer 422 Posting Pro

Well there are several methods , but I would go with the simplest...

Assume that you take the dimension of nxn martix as the input from the user where user feeds in value of n. And array[][] is the one in which he feeds in the value.

Just have another integer pointer as

int *ptr;

After the user feeds in the value of n you can allocate a linear array as

ptr=(int *)malloc(n*n*sizeof(int));

Use this array to sort your elements out using the pointer itself as index to the array as:

*(ptr+i)

or even as:

ptr[i]

Once you are done wit sorting then you can just free the memory as

free(ptr);

This would be just like using a temporary array for sorting.

Hope this helps... :)

csurfer 422 Posting Pro

You have used %i every where for scanning integer variables as:

scanf("%i", &n);

this is wrong the correct usage is,

scanf("%d", &n);

You need to correct this all throughout the program, and ya before calling the search function you need to call a function to sort the inputs and I didn't see any such function in your program.And I hope your search calling function is correct ;).

csurfer 422 Posting Pro

Well to solve this look a the matrix format... when we give an input the maximum number within the matrix is input square... that is if input is n then the maximum number feeded into the matrix will be n suqare.
Assume :
Array = a[][];
Input = n;
sq = n squared;

So take a variable num=0 and you have your input squared that is sq

while(num<sq)
{
// Coded for loops for traversal required,you may need upto 4 for //loops
}
csurfer 422 Posting Pro

Thanks everyone i was misguided by my own doubts.... ;) Thanks for helping.

csurfer 422 Posting Pro

For inserting a node at the beginning y the foll code wont work?

struct node
{
int data;
struct node *-next;
}*head,*run,*ptr;

Hey i think you missed out on the erreneous "-" sign behind next in

struct node *-next;

It should be

struct node * next;

And also the malloc is not used like this:

head=n*(malloc(sizeof(n));

it should be as this:

head=(n*)malloc(sizeof(n));
csurfer 422 Posting Pro

switch is used to SWITCH between things or choices.

Both, the developers of C language and also the people on this forum are quite witty...so take their wise words and do some research on the topic first before posting a question...thats the only way to learn things in a programming language.(Especially C,try writing more programs).

csurfer 422 Posting Pro

It seems it's your homework... See this forum rules... ;)
Some tips:
1. the scanner (lexical analyser) works "before" preprocessor so your 1st statement is wrong...
2. The C preprocessor is a one-pass text processor...

No buddy its not my homework and thanks to you moderators that I know how this community works and have great respects for it.

I searched for answers in http://c-faq.com and others too didn't find a satisfying answer so asking you guys to clear my own programming doubts.

#define is dealt with by preprocessor right and not lexixal analyser ?

And as preprocessor is a one pass text processor cyclic replacements is impossible right?

And my earlier query of why

#define int float

is still not clear...