@skydiploma:
The "==" comparision for strings given in namespace std is given only for strings of class string.
@KangarooBlood
Make the changes given in post #3 it will work.
And ya don't use abusive words on the forum please.
@skydiploma:
The "==" comparision for strings given in namespace std is given only for strings of class string.
@KangarooBlood
Make the changes given in post #3 it will work.
And ya don't use abusive words on the forum please.
Three small changes :
1>Use #include<string> in the beginning
2>Take name as
string name;
rather than char name.
3>Use "kevin" rather than 'kevin' in the check.
I really don't get why MrNoob is so obsessed with fflush(stdin);
and also with fputs
.And ya one more thing "Program Keeps reading wrong input".
It always just does what you have programmed it for.So the program is not wrong you are !!!
Rats! I looked right at that and skipped over it! Good catch CSurfer!
Don't let your eyes run ahead of your brains!!!:)
@wildgoose
You're entering pounds calling it dollars.
Pound as a unit of weight not as a monetary unit.
@MrNoob
1>toupper() is defined in <ctype.h>
and I don't see it in your headers.
2>
Even though the problems mentioned in above posts are right most of them are problems due to logical thinking "Tier" "Shipping cost" and all.Ya you calling artichokes for everything is a fault,but both of you failed to notice one major problem.
switch(scanf("%d",&groc))
Scanf returns the number of inputs it has successfully read not their value so if you feed in even 3 or 2 it has successfully read one input so it returns 1. So here you are not deciding the switch upon the choice of the user at all.Because on every successful read scanf returns 1 and the user is forcibly directed to choice 1 even if he chooses 3.
It should be as :
for(;;) //Your for statement only
{
// The stuff you have written before switch
scanf("%d",&groc);
switch(groc)
{
//Switch conditions
}
//Other stuff
}
You both need to concentrate on what stuff you are dealing with.This is C language and it requires some patience and some effort.
Some major problems :
1>Get a standard compiler for yourself. They are all free of cost.Boreland C and Tc and all are not going to take you anywhere.
2>The load function works fine better use the second method I had suggested for "for loop" rather than the one implemented.Because the present condition loops one time extra.But still works.Some bug may creep in so the suggestion.
3>Problem is with your view function.You are calling it as view(s,n);
.You cannot just pass any value for n you should keep a counter for total number of records in the file and that should be passed as n.Or atleast if you think that is users work to remember the number of records you atleast need to take the input for n before calling view as:
printf("Input the number records you want to view / input the number of records in file that you remember :");
scanf("%d",&n);
view(r,n)
It should be mainly implemented this is the function looping infinitely.With arbitrary value for n it will loop any random number of times.So infinite loop.
Post in your code or else attach the file.
I told you earlier itself that was just to show you the implementation.Thats it you need to research the things and work out for yourself. We here at Daniweb just show you the way we don't give you every details :)
Errors :
1> You cannot code like this.isdigit() is a function:
if isdigit(cResponse);
It should be
if(isdigit(cResponse));
2>Be sure of the portability of scanf_s
3>Your program has a lot of mistakes.
*
{
printf("\n\tThis program will determine if you are old enough to vote:\n");
printf("\n\tPlease enter your age; ");
scanf_s("%d, %c", &iResponse, &cResponse);
}
Useless Braces.
*The semicolon after your problematic if statement.With that its as good as not including that if statement.
*isdigit() checks for a digit 0 1 2 3 4 5 6 7 8 9 not for a number.
And many others so check.
And ya mainly use code tags.Is that so difficult???
I sense a problem here in your load file function :
for(ctr = 0; fp == 0; ctr++)
fread(&(r[ctr]), sizeof(studrec), 1, fp);
You can correct it as
size_t c;
for(ctr = 0; c != 0; ctr++)
c=fread(&(r[ctr]), sizeof(studrec), 1, fp);
Above code will take one extra loop to find the end so better
size_t c;
for(ctr = 0;; ctr++)
{
c = fread(&(r[ctr]), sizeof(studrec), 1, fp);
if(!c) break;
}
There are far better ways,this is just the least modification of your code.:)
And sorry salem this is happening second time with me today when I begin writin there would be no post and when I post it there would be a reply already...and we cant delete any post made :(
Not probably a crash but it will definitely crash the second time.Because the first delete will deallocate the memory reference with respect to pArray then second time when we try to deallocate the memory references we try for pArray[0] to pArray[9] but parray[0] is already de allocated by first statement.
Just use the second statement thats enough.
How come you are posting a problem about new and delete in a C forum ??? Its C++ forum you should post it in.
One of the problems I see is this
return *output;
It is actually returning output[0] here when you want it to return the address of output array.
It should just be
return output;
Sorry fellows Daniweb is loading too slow on my side so when I was posting I couldn't see your replies... ;)
@OP : If you had put in half of the effort what Vernon has put in the above post you would have solved your problem easily by now !!!
You are not lost after coding this much you are lost from the beginning...
Hell lot of mistakes :
1> [#include <iostream>
Typing mistake
2>
int
int main(void)
What is this form ???
3> cout <<a1[45]<<endl;
Segmentation fault illegal memory referenced alloted memory is from a1[0] to a1[44]
for declaration int a1[45];
4>
if (a2[50] % 5 ==0)
cout<<a2[50]<<endl;
Segmentation fault again
5> int max(0);
What is this exactly???
6>
if (a1[45] > max)
max = a1[45];
Segmentation fault again.
And USE CODE TAGS and for finding minimum and maximum you can follow this algorithm
int min,max;
//Loop through a1[] first and initialize min=max=a1[0]; Now for every i ahead
if(a1[i]<min) min=a1[i];
if(a1[i]>max) max=a1[i];
//Now loop through a2[] ,for every i
if(a2[i]<min) min=a2[i];
if(a2[i]>max) max=a2[i];
//YOu'll have both min and max values for both arrays combined.
Both of you are right.
Copy constructor is a constructor used only in situations where we come across situations two objects A and B of same class type assigned as
A=B;
I wanted to go with example
X a=X(X const& copyFromMe);
example but it ended up this way.(In making sure I don't give him the thing he seeks in a golden platter ;))
@ramthegreatcv : Ya its return value optimization and about the copy constructor I didn't find any other way to make you understand,so used this bizzare approach.
@tux4life :I was trying to explaining op the purposes of using a copy constructor with that,thats it,I know the way I took is hopeless.
Well how have you written the records in the file from which you are taking the input ?
Extras :
>Try not using .eof() function its not good to use it like this several times discussed already in this forum.
>And within the read looping you can always include a counter right to know how much you have read.
Answers:
1>Assume that there is a class as:
class check{
int a;
public:
check()
{
cout<<"Constructor";
}
check(int i)
{
//copy constructor code
}
void setvalue()
{
//sets value for a
}
};
//Inside main way 1 normal
check c;
c.setvalue();
//Inside main way 2 copy constructor
check c(5);
Above shown are the two types of initializations for initialising integer a within the class object.
First method is to call the setvalue function as we normally do to set value to that integer.But you can directly initialize the static variables present within the class object as
check c(5);
if you have written code for it properly.
2>Address of bA and aA are same I have answered already why.
3>Value of aInt and bInt cannot be same because you are returning the value of aInt so aInt's value gets assigned to bInt so their values are same but their addresses differ because they are separate variables.
4>I have already explained why the destructor is called at end of main only,its because aA is not destroyed at the end of fun2 its returned and assigned to bA so now after main destructor for this object is called and that is seen by you.
>Why doesn't this happen for primitive data types like int ,char or float ?
I really didn't get your question.But this will give you your answers I suppose. and also this and this.
To be frank I think you don't know the use of copy constructor at all so please read about it first and then ask your doubts if you don't mind.You need to brush up a lot.
@athlon32
Check your answers before posting.
1>
They are not, i ran it on my computer and i get 2 different addresses
The address should be same because the OP is returning the object b address and assigning it to a.
2>
I don't think so, I removed the function fun() and left only a, and it gave me both destructor/constructor messages...i think the des/con aren't being called on B :?
How can you ever get destructor and constructor after removing fun() object b is getting declared within fun().
3>
Because it should be like this:
class A{
int i;
public:
A(){
cout<<"default constructor\n";
}
~A(){
cout<<"default destrutor\n";
}
A(A& obj);
};and this:
A::A(A& obj)
{
i=obj.i;
cout<<"copy constructor\n";
};
You don't need to just a const suffices look at my post.
@ramthegreatcv
Answers :
>1. Why only 1 destructor is getting called.
Because even though you think you are dealing with two objects you are actually dealing with one,because when you used return b in fun(),what you are actually doing is returning the address of that object and assigning it to object a by the statement a=fun(); so only one object is under observation.Here destructor is called only for object a before returning from main.
>2. Why address of a and b are same.
Look at answer for 1.
>3. If I use copy …
Well I looked at your code and it has a bunch of problems :
Error 1:
If this itself is your final code then you don't need NextDay() and PreviousDay() functions at all.
Error 2:
weekdayT IncrementDay(weekdayT day,int pass){
int p=0;
int counter=0;
p-=pass;
if(pass<0){
if(day>p)
{
return weekdayT(day-p);
}
else
{
counter = day;
for(int i=0;i<p;i++)
{
counter--;
if(counter<1)
{
counter = 7;
}
}
return weekdayT(counter);
}
}
return weekdayT((day%7)+pass);
}
This return should be:
return weekdayT((day+pass)%7);
Error 3:
Your code gives correct result for
cout << "Increment " << IncrementDay(Tuesday,0);
as Increment 0 but for
cout << "Increment " << IncrementDay(Tuesday,-7);
it gives Increment 7 instead of Increment 0 which even though correct is logically wrong.
And ya a general instruction about functions like below if you really use them :
weekdayT NextDay(weekdayT day){
return weekdayT((day%7)+1);
}
Don't use a function call just for a single statement processing. As you know the processor needs to do a whole lot of stuff before calling a small function like this one too and in cases like this its nothing but waste of processor time.If you can incorporate functions as small as these in macros then it speeds up your program to a good extent.
Though not an error it helps you better your program so …
Hey MosaicFuneral you seem to love spam msgs....thats funny dude !!! :)
Every thing but this makes sense to me :
return weekdayT((day-1)%7);
Assuming that the other user function which you have written is going to send values from 0 to 6 only for a weekday(if you have written that properly;)) then (day-1)%7 makes absolutely no sense and is redundant after what you have checked in your if statement.Only day-1 is enough as %7 there checks a thing you already know(that the value is between 0 and 6).
Well a weird idea but you can even split the number into digits and store in a linked list or an array or something else... flex your brain and you will do great !!!
Many Many Happy Returns Of The Day !!! And Welcome....
>Should I learn how to do C++ in windows and then learn.. Linux shell scripting (did I say that right)?
Well if you ask me thats the easy way but I would suggest you to learn and practice according to standards so install the Ubuntu you have got download a standard version of gcc (for c) and g++ (for C++) and go on coding...
Well I'd like to tell two things :
1> I really didn't get how is your algorithm going to test if there is the thirteenth friday in that month or not.
Your program doesn't have any reference for the year and without that there is no way to check the total number of days from the years start and the computations you have done is something totally out of the way.
2>Here I am not correcting your algorithm but shortening it as you had asked.You can device a far better algorithm so try ;)
//calendar
#include<stdio.h>
#define s scanf
#define p printf
int main ()
{
int dw,dm,m;
p("plz enter dw, dm, m\n");
s("%d%d%d",&dw,&dm,&m);
//for Alldays taken together
while (!(dm>=1&&dm<=7)) dm=dm-7;
if(dm==dw) p("in this month there is a 13th friday\n");
else p("in this month there is no 13th friday\n");
return 0;
}
You are doing nothing but the above code.And to be frank above code does nothing ;). And ya never use void main,use int main get used to the standards.
Well one of the ways for the first questions as I thought is this.
1> Take an input number n from the user.
2> "x" is an empty variable.
3> You have "y" as a number under concern.
What you need to do is pick the rightmost n bits of y and make a decimal number from it and feed it into x.
So you can do this.
* Assume an integer variable temp=1;
* Run a loop n-1 times and within it do
temp<<1;
temp | 1;
* After this loop you just need to do y & temp.
* The above algorithm will fetch you the right most n bits of y.
So your answer for 2-6 is x = y & temp;
In the same way try to answer 2-7. ;) The above code will make your other bits of "y" as 0. So you take another variable say z = y for your computations so that you ll get the results and also y will remain unchanged.
C runs on some rules,you need to learn them before trying out something,and ya you cannot just translate a code to C and expect it to work.
int maxprimes;
int count = 1;
int value = 1;
int primes[maxprimes];
int composite;
int i = 1;
int j;
printf ("How many primes? ");
scanf ("%d", &maxprimes);
This is wrong. You are trying to take the value of maxprimes from the user and trying to allocate that much memory for the array primes. But as you can see compiler would have already allocated memory for that array and at that time
int primes[maxprimes];
doesn't have any meaning,so the segmentation fault.
What you can do is to take the value of maxprimes and then allocate memory for array,but in C
int maxprimes;
int count = 1;
int value = 1;
int composite;
int i = 1;
int j;
printf ("How many primes? ");
scanf ("%d", &maxprimes);
int primes[maxprimes];
something like this is not allowed.Because in C all data variable's should be declared and initialized before the first operational statement(say an assignment or a check.).Its memory also needs to be allocated priorly if you are allocating it statically.
Now coming to the solution : You need to use dynamic allocation of memory Do this :
//Within main function
int maxprimes;
int count = 1;
int value = 1;
int *primes;
int composite;
int i = 1;
int j;
printf ("How many primes? ");
scanf ("%d", &maxprimes);
//your solution …
> oh thanks man but coudlnt i change direct to buffer?
What directly to buffer ? You mean to say directly to str array right ? I wont say you can't . First you need to write it as you were writing earlier and then after it you need to clear all the memory blocks ahead of it.
That is if your squeezing leaves your str array at index 4 then you need to find the total memory blocks allocated for this array in main function(because thats where you are allocating it memory)and clear all the memory blocks allocated for this block ahead. (Which is the right "FORMAL" procedure...).
Shortcut :
After your str array is over written just move the index 1 block ahead and place '\0' character in it. Placing the '\0' character symbolises the end of string and compiler won't print ahead.
But be warned this method is sure to bring one or the other problem because you won't know where exactly to place the '\0' character.
And ya your program has whole lot of limitations :
1> Your program doesn't take every letter in string2 and delete it in string1.Because its not looping its just matching the indexes. If instead of NAM as second string i give MAN then even with these letters in string1 your code wont delete it because its just matching indexes.
In total :
Try to write a better code for your requisite because …
Well in that case say you have 6 characters in str array,then assuming that you overwrite first three characters in the exact way in which you want even then you are doing nothing with the left over's.
Well change your code as this :
#include <stdio.h>
void Squeeze2(char *str,char *save,char *required)
{
int i,x;
int buffer=0;//used to save stuff
// And ya make an habit of using null character rather than simple 0
for( i=0 , x=0 ; str[i]!='\0' && save[x]!='\0' ; i++, x++ ) {
if( str[i]!=save[x] ) {
required[buffer]=str[i];
buffer++;
}
}
}
int main(void)
{
char name[]="NAME";
char req[10];
Squeeze2(name,"NAM",req);
puts(req);
getchar();
return 0;
}
The code is not only weird its senseless. Firstly two pointers buffer and i manipulating the same char array so what it writes in the array in which condition is completely unpredictable it just depends on both the inputs.
And even by going by the function name "squeeze2" if the OP wants to squeeze the first or the second array then why so much redundant work it can even be achieved by inbuilt functions.
Well use getline function. It advances the file get pointer to next line automatically.Or even you can look upon f.seekg() function.
Here is an algorithm for it :
//open a file using fstream objects say file and functions like file.open() in input mode
// Create a string variable which can act as a buffer for holding the values
while(getline( <file descriptor value>, <buffer object>)!=NULL)
{
int key;
string skey,value;
//extract string value of key into skey and convert it into integer using istringstream
//extract string value of key into value
//With the help of a new fstream object write into the file you want it to.
//erase the buffer for providing space for next input using file.erase() function
}
@StuXYZ :
Several things from your question:
First the string part. You have many options (a) you can indeed use
insert but the method requires an iterator to define the position for insertion. (b) the easiest to use simply += e.gchar p='x'; std::string A("test"); A+=x; // A is now testx
Make sure that the examples you give are correct because in the above code what you have stated is wrong and it would give rise to a compiler error stating that char variable x not declared.
Its either :
char p='x';
std::string A("test");
A+=p;
// A is now testx
or better and simple do this :
//char p='x';//Not at all required
std::string A("test");
A+='x';
// A is now testx
"After reading all the above posts once" you will know your question itself has your answer.
1>Convert float to string.
2>Concatenate using srtcat or strncat as said by you or snprintf as said by Arkm.
When you know everything did you try to google out first?I think you lost your patience in the last step. !!! ;)
You have a problem with the whole program or just a part of it ? Because its really hard to scan through every part...
Well you get built in options for the things you have asked both in Dev-Cpp and also Code Blocks...Try them.
Well if you can control the output of a random function then it wont remain a RANDOM function right ??? :D
Well you can always do this.First assume a variable "a" which is defined as follows :
1>a=Some random number from 1 to 19 (%20) generated by some random number generating method.
2>Place 0 in this block of array as array[a]=0.
3>Now your are sure that the array has one zero and also in a random place generated by computer itself.
4>Now go on with your for loop as above itself and just skip the loop when i==a.
And ya you have loads of threads here at daniweb to make the random function better.Just have a look at these threads it may help.
I got how you are trying to generate the prime numbers but you have messed it up to a great extent.
>Assume another variable lim which has the maximum index of prime numbers stored in array p.That is if you have got 3 prime numbers p[1],p[2],p[3] then lim is 3 and a variable called flag which signifies divisible if 1 and not divisible if 0.
>Just after your
if (num<5)
for(j=1;j<=((num+1)/2);j++)
printf("%d,",p[j]);
else
{
for(j=1;j<=3;j++)
printf("%d,",p[j]);
step do this :
x=6;
while(x<num)
{
flag=0;//Signifies not divisible
for(i=1;i<=lim;i++)
{
if(x%p[i]==0)
{
flag=1; //shows its divisible
break;
}
}
if(flag==0)
{
p[++lim]=x;
}
x++;
}
//Print the array p[] from 1 to lim here and you are done.
Its just this much even if I follow your algorithm.You are just confused.Take time to view your code once and the optimized code given above.And ya put your codes within code tags from next time.
I suppose you are using some compiler like TC because if you try to do something like array[-1] in gcc then it gives a segmentation fault.
Actually the concept is like this.When you write a statement like
int array[10];
10 consecutive integer blocks are alloted in memory with name array which can be accessed as array. When you write array[-1] then it tries to access an integer block before the memory allocated for array.Hence is illegal memory access.Hence not a valid statement.
And
array[1] = *(array+1);
because as you know
array=&array[0]
,you can access the 2nd block of memory allocated for array or the [1]th block as array[1] or *(array+1) because
*(array+1)=*(&array[0]+1)
which means get the array starting address increment it by 1 so it will point to second block of memory then get its value by * operator.
I think you didn't understand what Ancient Dragon said.You are printing the array till 900 but the inputs may end at 10 itself right?
So take a variable say count inside while loop as:
count=0;
while (infile) {
getline(infile, pd.name[i], ',');
infile >> pd.age[i];
getline(infile, pd.favourite_colour[i], ',');
count++;
i++;
}
And then print array only till count as:
for(int i = 0; i < count; i++){}
Yes vmanes you are right. But the OP had to start somewhere so I thought this would be better to start with and later learning and bettering the code from his/her own mistakes.Even this could be a solution to start with :
while(f_ptr){....}
But best according to daniweb is to use this:
while(fgets(....)!=NULL){.....} //or to use
while(getline(....)!=NULL){.....}
Get more info here.
Well check out the uniqueness of the password because if numbers are used as passwords then in most substitution and some block ciphers you get the same encryption or decryption for two passwords. And the speed is ok I suppose 5000 chars per sec thats nearly 39 kbps.Well for this you need to check in with a network expert because the speed which we are talking about is not transmission speed its the pre-transmission work and is considered as a delay.
Well you don't even need to know the number of lines in the file.
Use this :
fstream f_ptr;
string str;
f_ptr.open(<filename>,ios::in);
while(!f_ptr.eof())
getline(f_ptr,str,<delimiter>);
This complies to your requirements when the fields are delimited by some value.
@gretty : Ancient Dragon is right its not efficient.
The above code works right ??? Then whats the problem ? Why isn't this thread marked solved ?
Your code doesn't involve any c++ concepts. It is completely a c code I should say.And I think you are getting confused the order of execution is :
printf("Enter Your Age: "); // Executes 1st
age = getInt(IsValidAge); // Executes 2nd
printf("Enter your driving test mark: "); //Executes 3rd
mark = getInt(IsValidMark); //Executes 4th
And this code involves a more subtle concept called function pointers.Read this.
The code getInt is called first which in turn executes the function IsValidAge and IsValidMark in lines :
if(IsValid != NULL)
{
valid = (*IsValid)(num,ErrMes);
}
This is the call by function pointers.
Well what are you aiming your text encryptor to work for? It just depends on the application for which you are designing it for. More over the efficiency of working of your encryptor also matters.If its fast but not a good encoder then its a waste. And what type of encryption are you using? I mean the kind of cipher ?
Well do you know what exactly you are doing or what you want to do ?
FILE *fopen(); // Why this ?
And what are you expecting the computer to display when you are just opening the file and closing it ?
finput = fopen(pfile, "r");
if(finput==NULL) {printf("Error: can't open the file.txt\n");return 2;}
else {printf("File opened successfully.\n");}
fclose(finput);
And why so much complexity?
char pfile[80];
printf ("Type number of input (between 1 to 3): ");
scanf ("%i", i); // Error here in scaning (no &)
if (i = 1)
pfile == "pf1";
else if (i = 2)
pfile == "pf2";
else if (i = 3)
pfile == "pf3";
else
{printf ("Invalid Input, the number should between 1 to 3!!!");}
finput = fopen(pfile, "r");
The complete thing above can be done just by:
char pfile[80];
printf ("Type number of input (between 1 to 3): ");
scanf ("%i",&i);
sprintf(pfile,"pf%d",i);
finput=fopen(pfile,"r");
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.
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.