work with .hpp files - c++

The codes in my main program are given below; here I read a file called test.dat and data of this file put in to my structure so for that I used a class called MyData (my_data.hpp).
int main()
{
// cout<<"this my program"<<endl; // when this delete, this codes are not working
bool ok=true;
MyData my_data("test.dat", ok);
if(ok==false){
cout<<"Error, unable to read file1.";
return 0;
}
ACalculation a_calculation(&my_data);
For the calculation part, I used another class, AClaculation (a_calculation.hpp). Here I used pointers to speedup my program.
ACalculation (MyData * my_data){
MYData::iterator i;
for (i= my_data ->begin(); i!= my_data ->end(); i++){
if(i->A() > max){
max = i->A();
}
}
cout<<”my max value is:”<<max;
My program does not show any errors but when I run it, it does not show the result of my max value. But when I added a “cout” code at the beginning of the main program then it shows the result. It means, when I delete this line:
cout<<""this my program";
the program does not show correct output. But when I add it again, it workq. I can't understand where the error of my program is?.
Please help me to find out my mistakes here.. thanks

I think you have to flush the console printing an endl

Related

Hello. Im trying to make a pyramid of strings with my name in it

What I'm trying to do:
#include<iostream>
#include<string>
using namespace std;
int main(){
string st("HabibRehman");
string a="", b="";
int y=st.length();
int d=y/2;
int f;
f=d;
for(int i=1;i<st.length();i++){
for( int j=0;j<y;j++){
cout<<" ";
}
for(int k=0;k<1;k++)/*I'm not sure what this loop should be*/{
cout<<a+st.substr(d,i)<<endl;
/*int d=(st.length()/2);
static int f=d;//I was trying to keep the values static here
static int g=d;*/
//this doesn't work in here
}
--f;//if i put this outside the for loop it works wrong without the termination error.
a=st.substr(f,i);//I'm using this to get the value prior to the st.substr(d,i)
y--;
}
system("pause");
return 0;
}
I keep getting a termination error. Ive tried almost everything I knew like changing the loops, the positions of substrings and variables, when I get the output I want, the program gives me an termination error, otherwise it gives me a wrong output without the termination error.
I do not fully understand this code, it really writed very bad.
But after 1,5 minutes of debugging I found that exception is thrown because f in a=st.substr(f,i); is lower than 0.
In for(int i=1;i<st.length();i++){ you decrement the variable f st.length() times, but f is half of st.length() and will get after st.length()/2 iterations -1 value.
I added after --f;
this statement:
if(f < 0 ) return 0;
and it seems that programm working well.
Please, learn how to write beatiful and readable code.

1D Peak, on execution says an error has caused the code to be stop working

I am trying to find the 1D peak through Divide and Conquer technique in this particular question,
my program even though it runs,
but at the time of giving the final output it says that there has been some problem with the execution,
I have got the answer from a different method, but I would like to know where am I at fault here.
#include<iostream>
using namespace std;
int a[8];
class pg1
{
public:
int func(int n)
{
if(a[n] <= a[n+1])
{
func(n++);
}
else if(a[n] <=a [n-1])
{
func(n--);
}
else
{
return n;
}
}
};
int main()
{
pg1 ob;
for(int i=0;i<8;i++)
{
cin >> a[i];
}
int x = ob.func(4);
cout << endl << x;
return 0;
}
Input-
5
6
8
5
4
3
6
4
Errors are-
1D Peak.exe has stopped working.
A problem caused the program to stop working correctly.Windows will close the program and notify you aif a solution is available.
End Result-
Process Exited with return value 3221225725
Don't use postincrement and similar in function calls.
Here's the problem condensed down to a really simple piece of code
#include <iostream>
int test(int n){
if(n == 1){
std::cout << "Function called!";
return test(n++);
}else{
return 0;
}
}
int main() {
test(1);
return 0;
}
Before you run this, ask yourself what you expect to happen here. Did it do what you thought?
When you run this you'll see that the code doesn't terminate properly. The output shows the function gets called infinitely many times, eventually the stack runs out of space and the program crashes.
You can see this code in action here: http://ideone.com/QL0jCP
In your program you have the same problem:
int func(int n)// say n = 4
{
if(a[n] <= a[n+1])//say this is true
{
func(n++); //this calls func(4) THEN increments n afterwards
}
This calls func with the same value over and over.
The solution is to not use postincrement or postdecrement in your function calls. These create hard to diagnose bugs as you have seen in this question. Just a simple func(n+1) is all you need. If you needed to use the variable later then just create an explicit variable to do that, it's much cleaner coding style (as this problem you ran into here shows).
After you fix this you'll need to fix your array bounds checking.
if(a[n] <= a[n+1])
If n is the last spot in the array you suddenly are trying to access one place past the end of the array, if you are lucky you get a segfault and a crash, if you are unlucky you get some bug that messes up your system that is hard to find. You want to check the values are valid.

c++ code magically add 1 to the output

So I can't figure this out. (obviously)
Basically the variable count is declared in the beginning, then only modified or incremented in one place. The expected final count is 78682. And when count is equal to that, I'll print out the string "ok". When count is incremented to 78683, the code checks the condition and prints the string "not ok".
It never prints "not ok", but at the very end when we print the value of the count, it's 78683! When did c++ incremented?
Another thing is that when the comment is uncommented below, the final result then becomes 78682, though I just don't understand why. Anyone? (oh btw, the code takes a minute to run....)
#include <stdio.h>
int main(){
int count=0, sum=0;
int length []={1,2,4,10,20,40,100,200};
int value [] ={200,100,50,20,10,5,2,1};
int tmp[8] ={0};
bool stop=false;
while(!stop){
sum=0;
for(int j=0,k=0; j<8; j++){
sum+=value[j]*tmp[j];
if(j==7){
if(sum==200){
count++;
if(count==73682) printf("ok\n");
if(count==73683) printf("not ok\n");
}
k=j;
tmp[k]++;
while(tmp[k]==length[k]+1){
tmp[k]=0;
k--;
tmp[k]++;
if(tmp[0]==2)
{
//tmp[0]--;
stop=true;
}
}
}
}
}
printf("Total %d.", count);
return 0;
}
On my computer I getting
ok
Total 73682.
both with the line commented and with the line uncommented. Therefore I can't debug it.
But the most probable assumption is that the reason you get wrong result is out-of-bounds array access. If you write tmp[anything] it can be any place in memory, including the place where count is stored. So you need to check that 0 <= anything && anything < 8. You can such an access here:
while(tmp[k]==length[k]+1){
tmp[k]=0;
k--;
please add safety checks to ensure k >= 0.
P.S. I added the check:
while(tmp[k]==length[k]+1){
tmp[k]=0;
k--;
if( k < 0 ) printf("oops\n");
with the line commented I get
ok
oops
Total 73682.
with the line uncommented I get
ok
Total 73682.
so probably you have some other mistake in the program. Sorry, can't find it. (Also knowing what the program suppose to do you can print intermediate results and check them. But you should see out of bounds access on you computer if you get 73683).

C++ program to compute lcm of numbers between 1 to 20 (project euler )

as the title explains this is a program to find lcm of numbers between 1 to 20. i found an algorithm to do this, here's the link
http://www.cut-the-knot.org/Curriculum/Arithmetic/LCM.shtml
there is a java applet on the webpage that might explain the algorithm better
Problem: i wrote the code compiler shows no error but when i run the code the program goes berserk, i guess may be some infinite loopig but i can't figure it out for the life of me. i use turbo c++ 4.5 so basically if anyone can look at the code and help me out it would be great . thanks in advance
Algorithm:
say we need to find lcm of 2,6,8
first we find the least of the series and add to it the number above it, i.e the series become
4,6,8
now we find the least value again and add to it the intitial value in the column i.e 2
6,6,8
so the next iteration becomes
8,6,8
8,12,8
10,12,8
10,12,16
12,12,16
14,12,16
14,18,16
16,18,16
18,18,16
18,18,24
20,18,24
20,24,24
22,24,24
24,24,24
as you can see at one point all numbers become equal which is our lcm
#include<iostream.h>
/*function to check if all the elements of an array are equal*/
int equl(int a[20], int n)
{
int i=0;
while(n==1&&i<20)
{
if (a[i]==a[i+1])
n=1;
else
n=0;
i++;
}
return n;
}
/*function to calculate lcm and return that value to main function*/
int lcm()
{
int i,k,j,check=1,a[20],b[20];
/*loading both arrays with numbers from 1 to 20*/
for(i=0;i<20;i++)
{
a[i]=i+1;
b[i]=i+1;
}
check= equl(a,1);
/*actual implementation of the algorith*/
while(check==0)
{
k=a[0]; /*looks for the least value in the array*/
for(i=0;i<20;i++)
{
if(a[i+1]<k)
{
k=a[i+1]; /*find the least value*/
j=i+1; /*mark the position in array */
}
else
continue;
}
a[j]=k+b[j]; /*adding the least value with its corresponding number*/
check= equl(a,1);
}
return (a[0]);
/*at this point all numbers in the array must be same thus any value gives us the lcm*/
}
void main()
{
int l;
l=lcm();
cout<<l;
}
In this line:
a[j]=k+b[j];
You use j but it is unitialized so it's some huge value and you are outside of the array bounds and thus you get a segmentation fault.
You also have some weird things going on in your code. void main() and you use cout without either saying std::cout or using namespace std; or something similar. An odd practice.
Also don't you think you should pass the arrays as arguments if you're going to make lcm() a function? That is int lcm(int a[], int b[]);.
You might look into using a debugger also and improving your coding practices. I found this error within 30 seconds of pasting your code into the compiler with the help of the debugger.
Your loop condition is:
while(n==1&&i<20)
So your equl function will never return 1 because if n happens to be 1 then the loop will just keep going and never return a 1.
However, your program still does not appear to return the correct result. You can split the piece of your code that finds the minimum element and replace it with this for cleanliness:
int least(int a[], int size){
int minPos = 0;
for(int i=0; i<size ;i++){
if (a[i] < a[minPos] ){
minPos = i;
}
}
return minPos;
}
Then you can call it by saying j = least(a, 20);. I will leave further work on your program to you. Consider calling your variables something meaningful instead of i,j,k,a,b.
Your equl function is using array indices from 0-20, but the arrays only have 1-19
j in lcm() is uninitialized if the first element is the smallest. It should be set to 0 at the top of the while loop
In the following code, when i=19, you are accessing a[20], which is out of the bounds of the array. Should be for(i=0;i<19;i++)
for(i=0;i<20;i++) {
if(a[i+1]<k)
You are not actually using the std namespace for the cout. this should be std::cout<<l
Your are including iostream.h. The standard is iostream without the .h, this may not work on such an old compiler tho
instead of hard-coding 20 everywhere, you should use a #define. This is not an error, just a style thing.
The following code does nothing. This is the default behavior
else
continue;

Program Crashes when I try to compare two strings in c++?

int removeContact(Contact *newPtr, int runningTotal)
{
//define variables
string remove;
int next;
//prompt user for name they wish to remove
cout << "Enter the name you would like to delete (Last name first): ";
cin.ignore();
getline(cin, remove);
for (int t=0; t<=runningTotal; t++)
{
if (remove.compare(newPtr[t].name) == 0)
{
//calls function moveArrayElements function
moveArrayElements(newPtr, runningTotal, t);
//decrement runningTotal
runningTotal--;
//prompt user contact was found
cout << "Contact was found and deleted!";
next=1;
}
}
if(next!=1)
{
cout<< "ERROR: Contact was not found!";
}
return runningTotal;
}
This function is apart of a larger c++ program that is designed to manage a persons contact information. This function is suppose to remove a contact.
The problem I'm have is with the if (remove.compare(newPtr[t].name) == 0) statement. When my program gets to this part of the code it will crash without giving any errors. I tried straight up comparing both the stings with == operator, but this still results in a crash of my program...
Also, what make this so strange is that this code works perfectly when the function is called while my program is running with the contact that I'm trying to remove not stored in a text file.
However, when I close my program, and load my contact information from the text file, my program will crash... I know that my program is reading the file into the proper string array because I have a print function, so I know that all of my contacts are being transferred into the proper structure arrays...
Any ideas on how I can fix this? Any help would be appreciated! Thanks
UPDATE: I took the suggestions in the comments and changed my for loop to
t<runningTotal;
However, when I do this my program doesn't crash, but it wont's compare the strings...
If runningTotal is the size of your array, then the range of valid elements is [0, runningTotal). In the below code, you're looping up to runningTotal inclusive, when there isn't a valid Contact object there:
for (int t=0; t<=runningTotal; t++)
{
if (remove.compare(newPtr[t].name) == 0)
Therefore when you go and dereference newPtr[t], for t = runningTotal and then try and get the name element, you'll be causing undefined behaviour and may cause a crash.
Try changing t<=runningTotal to t < runningTotal to see if the problem goes away.
Also, is there a reason why you're using arrays as opposed to an std::vector?
i guess the for statement should be:
for (int t=0; t<runningTotal; t++)